所以我试图在 jPanel 中的 jFrame 中显示图像。
(我想这就是在 jFrame 中显示 JPEG/PNG 的方式) 这就是我正在做的事情:
在 jFrame 的构造函数中,我下载图像,动态创建 ImageIcon 和 jLabel(设置图标),并将其插入 jPanel 中。
我之前使用 NetBeans IDE 创建了 jPanel,其中 jPanelImage 在 initComponents() 中定义。
如果我使用调试器检查代码,他会正确下载图像而不会引发任何异常。
它也可以正常运行代码,没有任何问题。
但是我的 jFrame 仍然是空的。 代码如下:
public TransmissionFrame() {
initComponents();
init();
}
private void init() {
JLabel label = new JLabel("Java Technology Dive Log");
ImageIcon image = null;
try {
image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png")));
} catch(MalformedURLException mue) {
mue.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
label.setIcon(image);
jPanelImage.add(label);
jPanelImage.validate();
}
但是我的jFrame和jPanel仍然是空的,为什么?
最佳答案
更新,为 JPanel 分配布局可能是解决方案
public TransmissionFrame() {
initComponents();
init();
}
private void init() {
JLabel label = new JLabel("Java Technology Dive Log");
ImageIcon image = null;
try {
image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png")));
} catch(MalformedURLException mue) {
mue.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
label.setIcon(image);
jPanelImage.setLayout(new FlowLayout());
jPanelImage.add(label);
}
关于java - 图像未显示在 jPanel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39298796/