【问题标题】:This POOR JLabel shows the picture only after RESIZING The Frame. Why?这个糟糕的 JLabel 仅在调整框架大小后才显示图片。为什么?
【发布时间】:2021-09-24 12:05:55
【问题描述】:

这对我来说是最简单的代码.. 但无法从我的桌面显示我上传的图片,而是当我用鼠标调整 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);

【问题讨论】:

  • 您在添加标签之前显示框架。因此,只有当您调整框架的大小时,它才会重新渲染并看到图像。您应该首先添加标签,然后调用 .pack() 和 .visible()。希望对你有帮助
  • 添加 JLabel 组件后,您必须设置 setSize 和 setVisible。
  • 1) 为了尽快获得更好的帮助,edit 添加minimal reproducible exampleShort, Self Contained, Correct Example。 2) 例如,获取图像的一种方法是热链接到在this Q&A 中看到的图像。例如。 this answer 中的代码热链接到嵌入在this question 中的图像。
  • 顺便说一句。奇怪的是,这个 // f.setLayout(new FlowLayout()); 被注释掉了,并且代码试图将 2 个标签(没有指定约束)添加到 BorderLayoutJFrame 的内容窗格的默认布局)。只有一个会显示,但设置 FlowLayout 将是一种解决方法。 .. 在我的示例中,我将它从两个组件减少到一个组件,这真是太幸运了——这也可以。

标签: java swing user-interface jframe


【解决方案1】:

这是一个 MRE / SSCCE,演示如何加载图像并将其显示在正确大小的框架中。阅读代码 cmets 以获得进一步的解释。

请注意,代码可能使用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);
    }
}

【讨论】:

  • 优秀.. wowwwww .. 非常感谢你……亲爱的@Andrew Thompson
猜你喜欢
  • 2014-04-10
  • 1970-01-01
  • 2012-09-24
  • 2011-11-25
  • 2018-02-24
  • 1970-01-01
  • 2021-07-20
相关资源
最近更新 更多