【发布时间】:2013-07-19 03:21:56
【问题描述】:
我一直在到处寻找解决方案,并阅读了一些与此问题相关的类似帖子,但没有一个对我有用。
我正在尝试在 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()));
}
}
}
图像位于名为 images 的文件夹中,该文件夹位于 Gui.java 文件和 TESTMain.java 文件旁边的 src 文件夹中。
我得到的错误是来自 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() 是首选,因为图像需要与 jar 一起编译。
关于让我的图像显示的任何想法?
【问题讨论】:
-
将
getResource("images/imageA.png")更改为getResource("/images/imageA.png")。
标签: java swing png embedded-resource imageicon