ImageIcon和按钮上的图像问题 - JFrame

时间:2012-07-24 23:39:17

标签: java image swing jframe embedded-resource

这一直让我疯狂,所以我想我会把它发布在这里,看看是否有其他人可以解决这个问题。首先,我试图添加一个背景图像,默认的ImageIcon没有工作,所以我改为覆盖paint方法。 #

public class ImageJPanel extends JPanel { 
private static final long serialVersionUID = -1846386687175836809L;
Image image = null; 

public ImageJPanel(){ 
    addComponentListener(new ComponentAdapter() { 
    public void componentResized(ComponentEvent e) { 
        ImageJPanel.this.repaint(); 
    } 
}); 
}
//Set the image.
public ImageJPanel(Image i) { 
  image=i; 
  setOpaque(false); 
} 
//Overide the paint component.
public void paint(Graphics g) { 
  if (image!=null) g.drawImage(image, 0, 0, null); 
  super.paint(g); 
} 

}

一旦我使用它,它工作正常,但现在我想添加图像到我的按钮,但它不起作用。以下是我的按钮的工作方式:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Images images = new Images();
JPanel j = new ImageJPanel(images.menuBackground); 
j.setLayout(null);
JButton Button_1= new JButton("Button_1",new ImageIcon("images/gui/Button.png"));

Insets insets = j.getInsets();
Dimension size = Button_1.getPreferredSize();
Button_1.setBounds(300 + insets.left, 150+ insets.top, size.width, size.height);

Singleplayer.setSize(200, 50);

j.add(Button_1);

frame.add(j);
frame.setSize(800,600);
frame.setResizable(false);
Button_1.addMouseListener(singleplayerPressed);

frame.setVisible(true);

我的所有图片都是.png,会对它产生影响吗?

2 个答案:

答案 0 :(得分:2)

让我们从这开始:

public void paint(Graphics g) { 
    if (image!=null) g.drawImage(image, 0, 0, null); 
    super.paint(g); 
} 

这是错误的做法。首先,你真的不想覆盖绘画方法,除非你绝对知道这是解决你的问题的正确方法(并且不知道更多,我建议不要)。

其次,您在组件上绘制图像,然后立即在其顶部绘制...(super.paint(g);可以绘制您的工作,我知道面板是不透明的,但这是仍然是一个非常糟糕的方法。)

使用paintComponent代替

protected void paintComponent(Graphics g) { 
    super.paint(g); 
    if (image!=null) g.drawImage(image, 0, 0, null); 
} 

PNG图片很好,开箱即可支持Swing。

确保您的程序可以看到图像。它是从文件源加载还是JAR中的资源?

试试这个:

System.out.println(new File("images/gui/Button.png").exits());

如果您的程序可以看到该文件,它将返回true,否则程序无法看到该文件,这就是您的问题。

答案 1 :(得分:2)

试试这个:

ImageIcon image = new ImageIcon(this.getClass()
                .getResource("images/gui/Button.png"));

旁注,您应该覆盖paintComponent()而不是paint()。还要确保在完成所有绘画之前调用super implementation 。有关详细信息,请参阅Lesson: Performing Custom Painting教程。