这让我一整天都发疯,所以我想我应该把它发布在这里,看看其他人是否可以解决这个问题。首先,我尝试添加背景图像,默认的 ImageIcon 不起作用,所以我改写了绘画方法。 #
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,这会影响吗?
最佳答案
让我们从这里开始:
public void paint(Graphics g) {
if (image!=null) g.drawImage(image, 0, 0, null);
super.paint(g);
}
这是错误的做法。首先,你真的不想重写paint方法,除非你绝对知道这是解决你的问题的正确方法(如果不知道更多,我建议它不是)。
其次,你在组件上绘制你的图像,然后立即在它的顶部绘制...(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
,否则程序无法看到该文件,这就是您的问题。
关于java - ImageIcon 和按钮上的图像的问题 - JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11640821/