[英]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.