【问题标题】:Image not being displayed in jPanel图像未显示在 jPanel 中
【发布时间】:2017-01-10 22:44:27
【问题描述】:

所以我尝试在 jFrame 内的 jPanel 中显示图像。

(我想这是在 jFrame 中显示 JPEG/PNG 的方式) 这就是我正在做的事情:

在jFrame的构造函数中,我下载图片,动态创建ImageIcon和jLabel(设置图标),并将其插入到jPanel中。

我之前使用 NetBeans IDE 创建了 jPanel,jPanelImage 是在 initComponents() 中定义的。

如果我使用调试器检查代码,他会下载图像属性而不会引发任何异常。

它还可以正常运行代码而没有任何问题。

但是我的 jFrame 仍然是空的。 代码如下:

    public TransmissionFrame() {
        initComponents();

        init();
    }

    private void init() {

    JLabel label = new JLabel("Java Technology Dive Log");
    ImageIcon image = null;
    try {
        image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png")));
    } catch(MalformedURLException mue) {
        mue.printStackTrace();
    } catch(IOException ioe) {
        ioe.printStackTrace();
    } 
    label.setIcon(image);
    jPanelImage.add(label);
    jPanelImage.validate();
}

但是我的jFrame和jPanel还是空的,为什么?

【问题讨论】:

  • 您是否将 jPanelImage 添加到您的 JFrame 中?
  • 是的,我是用 NetBeans 静态创建的
  • 您需要将标签的初始化和标签的添加移动到 try catch 块中。我还将 JLabel 声明本身移到那里并尝试 JLabel label = new JLabel(image);然后给面板添加标签。
  • 我用调试器遍历了try块,我没有得到任何异常,但是我尝试了你说的,我得到了相同的结果
  • jPanelImage 在哪里添加到 JFrame 的内容窗格中?同样,minimal reproducible example 将非常有用

标签: java swing jpanel jpeg imageicon


【解决方案1】:

更新,为您的 JPanel 分配布局可能是解决方案

 public TransmissionFrame() {
        initComponents();

        init();
    }

 private void init() {
JLabel label = new JLabel("Java Technology Dive Log");
ImageIcon image = null;
try {
    image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png")));
} catch(MalformedURLException mue) {
    mue.printStackTrace();
} catch(IOException ioe) {
    ioe.printStackTrace();
} 
label.setIcon(image);
jPanelImage.setLayout(new FlowLayout()); 
jPanelImage.add(label);

}

【讨论】:

  • size of the panel 如果 Container 使用 LayoutManager,setSize 将不会做任何事情,并且 LayoutManager 应该适当调整包含 Icon 的 JLabel 的大小。见stackoverflow.com/questions/1783793/…
【解决方案2】:
jPanelImage.setVisibility(true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 2017-08-02
    • 2016-07-23
    • 1970-01-01
    • 2010-11-17
    • 2013-02-25
    相关资源
    最近更新 更多