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

标签 java image swing jframe embedded-resource

这让我一整天都发疯,所以我想我应该把它发布在这里,看看其他人是否可以解决这个问题。首先,我尝试添加背景图像,默认的 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/

相关文章:

java - 如何访问服务层的Session信息?

image - WebView 到 TIFF 表示

jquery - 同时在两个单独的列中延迟加载图像

javascript - jQuery上传错误: Uncaught TypeError: Cannot read property 'queueData' of undefined

java - 如何在Java中修改或添加JComboBox中的项目

java - AsynchronousSocketChannel Read/WritePendingException - 可以同步吗?

java - Eclipse 的 LogCat 被 Android 的 WAIT_FOR_CONCURRENT_GC 淹没

java - 如何在jTable中的某个单元格上获取jComboBox?

java - 从 Map 中的对象检索值

java - GUI、BoxLayout 添加面板