我正在尝试将图像“Pic.png”添加到此 JLabel“label1”中,并将其显示在 JFrame“window1”上的 JPanel“panel1”上。但是当我点击运行时它不会显示我的图像。有人帮忙吗? (我读到有关将其添加到源文件或其他内容的内容,但我不太确定我在做什么,因为我是 Java 新手。如果图像不在源中,它是否无法访问图片?)
public class UIForIshidaQuery {
public static void main(String[] args) {
System.out.println("Running...");
JFrame window1 = new JFrame();
window1.setVisible(true);
window1.setSize(1080, 720);
window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = (JPanel) window1.getContentPane();
JLabel label1 = new JLabel();
panel1.setLayout(null);
ImageIcon image = new ImageIcon("C:\\Users\\BC03\\Pictures\\Saved Pictures\\Other\\Pic.png");
label1.setIcon(image);
label1.setBounds(500, 500, 500, 500);
panel1.add(label1);
}
}
最佳答案
该窗口应设置为最后一次调用时可见。不要使用 null
布局1。这有效。
import java.net.*;
import javax.swing.*;
public class UIForIshidaQuery {
public static String url = "/image/gJmeJ.png";
public static void main(String[] args) throws MalformedURLException {
System.out.println("Running...");
JFrame window1 = new JFrame();
window1.setSize(1080, 720);
window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = (JPanel) window1.getContentPane();
JLabel label1 = new JLabel();
//panel1.setLayout(null);
ImageIcon image = new ImageIcon(new URL(url));
label1.setIcon(image);
//label1.setBounds(500, 500, 500, 500);
panel1.add(label1);
window1.setVisible(true);
}
}
- Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作,在不同的区域设置中使用不同的 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them以及 white space 的布局填充和边框.
关于java - 尝试将图像添加到标签但不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39141275/