【问题标题】:error: no suitable method found for add(BufferedImage)错误:找不到适合 add(BufferedImage) 的方法
【发布时间】:2014-02-04 13:59:44
【问题描述】:

我想知道我遇到的错误。我正在尝试使用 bufferedimage 类在 jframe 上设置单个像素,但由于某种原因,当我尝试将它们添加到框架时,我收到一条错误消息,指出没有找到合适的方法。

这是我的代码,有人可以告诉我如何将缓冲图像添加到框架中。

import javax.swing.JFrame;
import java.awt.image.BufferedImage;

public class gui {

  public static void main(String[] args) {
    int width = 40;
    int height = 80;
    int[] data = new int [width * height];
    JFrame frame = new JFrame("gui");
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    image.setRGB(0, 0, width, height, data, 0, width);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(image);
    frame.setSize(400, 400);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    }
}

错误:

gui.java:15: error: no suitable method found for add(BufferedImage)
    frame.add(image);
         ^
     method Container.add(Component,Object,int) is not applicable
      (actual and formal argument lists differ in length)
    method Container.add(Component,Object) is not applicable
      (actual and formal argument lists differ in length)
    method Container.add(Component,int) is not applicable
      (actual and formal argument lists differ in length)
    method Container.add(String,Component) is not applicable
      (actual and formal argument lists differ in length)
    method Container.add(Component) is not applicable
      (actual argument BufferedImage cannot be converted to Component by method invocation conversion)
    method Component.add(PopupMenu) is not applicable
      (actual argument BufferedImage cannot be converted to PopupMenu by method invocation conversion)
1 error

【问题讨论】:

  • 不是 100% 相关的,但它应该有助于引导您找到答案:stackoverflow.com/a/1065014/1786065ImageIcon 包裹在 Container 中可能是另一条路线,但尚未测试。
  • 错误本身是因为,如前所述,没有接受该对象类型的方法。

标签: java swing bufferedimage pixels


【解决方案1】:

您可以将BufferedImage 传递给ImageIcon,然后将ImageIcon 传递给JLabel。最后,添加这个JLabel,它只包含你的图片,就像你添加其他JLabel一样。

【讨论】:

    【解决方案2】:

    正如错误消息JFrame#add 已经指出的那样,对于BufferedImage 等非组件未定义。你可以这样做

    frame.add(new JLabel(new ImageIcon(image)));
    

    【讨论】:

      猜你喜欢
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多