我的 imageIcon 不工作?
我正在尝试设置一个 JFrame imageIcon,但由于某种原因它没有显示在 JFrame 中.
I am trying to set a JFrame imageIcon and for some reason it is not displaying in the JFrame.
ImageIcon img = new ImageIcon("stop.jpg");
frame.setIconImage(img.getImage());
我创建了一个 ImageIcon 变量,然后将该变量用于 getImage(),但它不起作用.有什么原因它不起作用吗?
I create an ImageIcon variable and then uses that variable to getImage() and it does not work. Is there a reason that it does not work?
问题:为什么 ImageIcon 不起作用?
类:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.ImageIcon;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import java.awt.Toolkit;
public class TestMenu extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel myPanel;
private static void setLookFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) { }
}
public static void main(String[] args) {
setLookFeel();
ImageIcon img = new ImageIcon("stop.jpg");
TestMenu frame = new TestMenu();
frame.setIconImage(img.getImage());
frame.setVisible(true);
}
public TestMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("TestA");
menuBar.add(mnNewMenu);
JMenuItem Item1 = new JMenuItem("TestAA");
Item1.addActionListener(new MyMenuListener(Item1));
mnNewMenu.add(Item1);
JMenu Item2 = new JMenu("TestB");
menuBar.add(Item2);
JMenu Item3 = new JMenu("TestBB");
Item2.add(Item3);
JMenuItem Item4 = new JMenuItem("TestBB-B");
Item4.addActionListener(new MyMenuListener(Item4));
Item3.add(Item4);
myPanel = new JPanel();
myPanel.setBorder(new EmptyBorder(25, 25, 25, 25));
myPanel.setLayout(new BorderLayout(10, 10));
setContentPane(myPanel);
}
}
推荐答案
你的图片保存在哪里?您的图片路径可能不正确:
Where is your image saved? It is possible the path to your image is not correct:
ImageIcon img = new ImageIcon("stop.jpg");
您应该使用基于您的班级的路径.这里例如图片存储在包图片中.
You should use a path that is based on your class. Here for example the image is stored in the package images.
new ImageIcon(MyClass.class.getResource("/images/image.png"));
相关文章