【问题标题】:Issues with ImageIcon and images on buttons - JFrame按钮上的 ImageIcon 和图像问题 - JFrame
【发布时间】:2012-07-24 23:39:17
【问题描述】:

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

【问题讨论】:

  • 图片在哪里? PNG工作得很好。旁注,您应该覆盖paintComponent() 而不是paint()。还要确保在完成所有绘画之前调用super 实现。
  • 1) 对于JPanel 覆盖paintComponent(Graphics) 而不是paint(Graphics) 2) 使用Class.getResource(String) 来定位图像等应用程序资源(代码提供了String,它将被解释为File 路径。3) 为了尽快获得更好的帮助,请发布SSCCE。 4)请学习常用的Java naming conventions(特别是用于名称的大小写)用于类、方法和属性名称并始终如一地使用它。

标签: java image swing jframe embedded-resource


【解决方案1】:

让我们从这个开始:

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 否则程序无法看到该文件,那是您的问题。

【讨论】:

  • g.drawImage(image, 0, 0, null); 最好是g.drawImage(image, 0, 0, this); // every JComponent is an ImageObserver!
  • 啊!非常感谢!这解决了问题!图片放错地方了。
  • @AndrewThompson Copy'n'Paste +1,总是让我保持警惕;)
【解决方案2】:

试试这个:

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

旁注,您应该覆盖paintComponent() 而不是paint()。还要确保在完成所有绘画之前调用super 实现。更多详情见Lesson: Performing Custom Painting教程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多