[英]This POOR JLabel shows the picture only after RESIZING The Frame. Why?
这对我来说是最简单的代码......但无法从桌面显示我上传的图片,而是当我用鼠标调整 JFrame 窗口的大小时,它会显示出来。
这种情况在 Netbeans 和 Eclipse 中都会发生……你能解释一下这背后的原因吗???? 提前致谢..
JFrame f=new JFrame("My Frame");
f.setSize(1500,1500);
f.setVisible(true);
// f.setLayout(new FlowLayout());
JLabel l=new JLabel("A pic in next Label");
f.add(l);
JLabel lp=new JLabel();
lp.setIcon(new ImageIcon("aaa.jpg"));
f.add(lp);
这是一个 MRE / SSCCE,演示如何加载图像并将其显示在正确大小的框架中。 阅读代码注释以获得进一步的解释。
请注意,代码可能会使用EmptyBorder
来表示标签周围的空白。 但我想证明它不是比需要的更大(或更小)的像素。
import javax.swing.*;
import java.net.URL;
public class DisplayAndSizeAnImageFrame {
// pathetic exception handling used here, BNI
DisplayAndSizeAnImageFrame() throws Exception {
JFrame f = new JFrame("Image Frame");
//f.setSize(1500,1500); Just a guess. Use pack() for right size
//f.setVisible(true); not YET
JLabel l=new JLabel("A pic in this label");
f.add(l);
// JLabel lp=new JLabel(); Don't need to use TWO labels!
l.setIcon(new ImageIcon(new URL("https://i.stack.imgur.com/P59NF.png")));
// Image from http://stackoverflow.com/q/19209650/418556
// now all components are added, size the frame..
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
Runnable r = () -> {
try {
new DisplayAndSizeAnImageFrame();
} catch (Exception ex) {
ex.printStackTrace();
}
};
SwingUtilities.invokeLater(r);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.