我需要 jframe 上的图像图标,但我不想给出路径。 我正在用这个
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\ABC\\Desktop\\folder name\\1.jpg"));
因为每个系统都有不同的路径,这就是我无法在其他系统(计算机)上编译它的原因。
我需要某种方法,以便我可以仅通过文件名设置图像图标。图像位于 src
文件夹中。
最佳答案
将Image
读取为嵌入式资源。此处显示的新 images
文件夹只需在类路径上可用
public class ImageApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Image image = null;
try {
image = ImageIO.read(getClass().getResource("/images/1.png"));
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Image App");
frame.add(new JLabel(new ImageIcon(image)));
frame.pack();
frame.setVisible(true);
}
});
}
}
关于java - JFrame 的图标路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615932/