Java JButton图像图标未显示.png文件
我一直在到处寻找解决这个问题的方法,也读过一些类似的帖子,但是没有一篇对我有用 我试图在JButton上显示图像“b.png”,当我滚动按钮时,图标会改变Java JButton图像图标未显示.png文件,java,swing,png,embedded-resource,imageicon,Java,Swing,Png,Embedded Resource,Imageicon,我一直在到处寻找解决这个问题的方法,也读过一些类似的帖子,但是没有一篇对我有用 我试图在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.Imag
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()));
}
}
}
图像位于名为images的文件夹中,该文件夹位于src文件夹中Gui.java
文件和TESTMain.java
文件旁边
我得到的错误是来自Main的空指针异常。我试过了
Icon b = new ImageIcon("images/imageA.png");
这会编译,但不会显示图像。我也试过了
custom = new JButton("custom", new ImageIcon("images/imageA.png"));
及
我知道,getClass().getResource()
是预先提供的,因为图像需要用jar编译
关于显示我的图像有什么想法吗?您的图像文件夹需要与编译的
.class
文件位于同一文件夹中,而不是与.java
文件一起位于src
。将getResource(“images/imageA.png”)
更改为getResource(/images/imageA.png”)
。
custom = new JButton("custom", new ImageIcon(getClass().getResource("images/imageA.png"));