【发布时间】:2021-08-06 00:28:03
【问题描述】:
我很困惑如何在 java 中将图像添加到我的 GUI。下面是我的代码,我使用ImageIcon 来实现图像“map.png”,但是当我运行这个程序时,图像没有出现。这是因为它与我的 .java 文件不在同一个文件夹中还是有其他问题?
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI implements ActionListener
{
private int count = 0;
private JLabel label;
private JFrame frame;
private JPanel panel;
public GUI()
{
frame = new JFrame();
frame.setResizable(false);
ImageIcon icon = new ImageIcon("map.png");
JLabel picture = new JLabel(icon);
JButton button = new JButton("Click me");
button.addActionListener(this);
label = new JLabel("Number of clicks: 0");
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(400, 700, 10, 30));
panel.setLayout(new GridLayout(0, 1));
panel.add(button);
panel.add(label);
frame.add(picture);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Maynooth Thing");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
new GUI();
}
@Override
public void actionPerformed(ActionEvent e)
{
count++;
label.setText("Number of clicks: " + count);
}
}
【问题讨论】:
-
您的代码是否生成错误消息?您是否在尝试创建 ImageIcon 变量
icon后检查它是否为空?请注意,您的图像应作为资源而不是文件获取,使用this.getResource(...)和ImageIO.read(...),然后放入ImageIcon。 -
这是因为它与我的 .java 文件不在同一个文件夹中 - 它应该与您的 .class 文件或类路径上的某个其他目录在同一个文件夹中.阅读 How to Use Icons 上的 Swing 教程,了解将图像文件作为资源读取的更好方法。
-
1) 应用程序资源在部署时将成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。 2) 正如@HovercraftFullOfEels 所述,最好使用
ImageIO加载图像,因为如果找不到图像,它将提供有用的输出。 3) 以后请尝试搜索该网站,这个或类似的问题必须每 48 小时询问一次。
标签: java image swing embedded-resource imageicon