2013-07-19 61 views
3

我一直在寻找解决方案,并阅读一些类似的帖子,但这些问题都没有为我工作。JButton Image Icon无法显示.png文件

我试图在JButton上显示图像“b.png”,当我滚动按钮时,图标发生变化。

package GUI_JButton; 

import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.Icon; 
import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 

public class Gui extends JFrame { 

    private JButton reg; 
    private JButton custom; 

    public Gui() { 
     super("Title goes here"); 
     setLayout(new FlowLayout()); 

     reg = new JButton("reg button"); // create reg button 
     add(reg); // add reg button to JFrame 

     // initialize images 
     Icon b = new ImageIcon(getClass().getResource("images/imageA.png")); 
     Icon x = new ImageIcon(getClass().getResource("images/imageB.png")); 

     custom = new JButton("custom button", b); // create custom button 
     custom.setRolloverIcon(x); 
     add(custom); // add button to JFrame 

     HandlerClass handler = new HandlerClass(); 
     reg.addActionListener(handler); 
     custom.addActionListener(handler); 

    } 

    private class HandlerClass implements ActionListener { 

     public void actionPerformed(ActionEvent event) { 
      JOptionPane.showMessageDialog(null, 
        String.format("%s", event.getActionCommand())); 

     } 

    } 

} 

的图像是这是在src文件夹旁边的Gui.java文件和TESTMain.java文件的文件夹命名为图像。

我得到的错误是来自Main的空指针异常。我试过

Icon b = new ImageIcon("images/imageA.png"); 

这个编译但图像不显示。我也曾尝试

custom = new JButton("custom", new ImageIcon("images/imageA.png")); 

而且

custom = new JButton("custom", new ImageIcon(getClass().getResource("images/imageA.png")); 

我知道作为图像需要用罐子来编译的getClass().getResource()被prefferred。

任何想法让我的图像显示?

+0

将'getResource(“images/imageA.png”)'改为'getResource(“/ images/imageA.png”)'。 –

回答

4

您的图片文件夹需要与您编译的.class文件位于同一文件夹中,而不是src与您的.java文件。

+0

这工作,谢谢队友。 – David