这个 POOR JLabel 仅在调整框架大小后才显示图片。为什么?
This POOR JLabel shows the picture only after RESIZING The Frame. Why?
这对我来说是最简单的代码..但无法显示我从桌面上传的图片,而是当我用鼠标调整 JFrame window 大小时,它会显示。
这种情况在 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
表示白色 space。但我想证明它不会比需要的像素大(或小)。
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
// 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);
}
}
这对我来说是最简单的代码..但无法显示我从桌面上传的图片,而是当我用鼠标调整 JFrame window 大小时,它会显示。
这种情况在 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
表示白色 space。但我想证明它不会比需要的像素大(或小)。
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
// 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);
}
}