这让我一整天都发疯了,所以我想我会把它贴在这里,看看其他人是否能解决这个问题。首先,我尝试添加背景图像,默认的 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,这会影响它吗?