简体   繁体   English

此 POOR JLabel 仅在 RESIZING The Frame 后才显示图片。 为什么?

[英]This POOR JLabel shows the picture only after RESIZING The Frame. Why?

This is the simplest code to me.. yet failing to show up my uploaded picture from my desktop, Rather when I resize the JFrame window with mouse, it shows up.这对我来说是最简单的代码......但无法从桌面显示我上传的图片,而是当我用鼠标调整 JFrame 窗口的大小时,它会显示出来。

This case happens both in Netbeans and Eclipse... can you explain the reason behind this????这种情况在 Netbeans 和 Eclipse 中都会发生……你能解释一下这背后的原因吗???? Thanks in advance..提前致谢..

    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);

This is an MRE / SSCCE that demonstrates how to load an image and display it in a correctly sized frame.这是一个 MRE / SSCCE,演示如何加载图像并将其显示在正确大小的框架中。 Read the code comments for further explanations.阅读代码注释以获得进一步的解释。

在此处输入图片说明

Note, the code might use an EmptyBorder for white space around the label.请注意,代码可能会使用EmptyBorder来表示标签周围的空白。 But I wanted to demonstrate it is not a pixel bigger (or smaller) than needed.但我想证明它不是比需要的更大(或更小)的像素。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM