JPanel不会显示在JFrame中

时间:2012-07-04 19:59:37

标签: jframe jpanel

我正在制作一个可以从互联网上加载图片的JFrame。我有这个工作,但这个JFrame的问题是有很多图片,所以他们需要很长时间才能加载。这很好,但我想向用户显示图片正在加载。出于某种原因,我无法在加载JFrame中显示JPanel。我知道这是一个常见错误,我尝试了很多修复,但没有一个能够正常工作。这是代码:

final JFrame weatherLoadPop=new JFrame("Loading weather...");
weatherLoadPop.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
weatherLoadPop.addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent e) {
      weatherPop.dispose();
   };
});
weatherLoadPop.setResizable(false);
weatherLoadPop.setBounds(100,50,225,100);
JPanel weatherLoadPanel=new JPanel();
weatherLoadPanel.setBackground(Color.RED);

weatherLoadPanel.setPreferredSize(new Dimension(225,100));
JLabel weatherLoadLabel=new JLabel("Loading...0%");
weatherLoadPanel.add(weatherLoadLabel);
weatherLoadPop.add(weatherLoadPanel);
weatherLoadPop.pack();
weatherLoadPop.validate();
weatherLoadPop.setVisible(true);

我不确定我是否正确使用pack()和validate()。我不经常使用它们。在任何情况下,删除它们都无济于事。对我来说,这个问题中最奇怪的部分是,加载图片的JFrame工作得非常漂亮,而加载JFrame则更简单。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这里的工作正常。也许您应该提供我们可以测试的sscce

我必须更改您的事件监听器以处理weatherLoadPop而不是weatherPop并将您的代码添加到测试类中:

package test;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        final JFrame weatherLoadPop = new JFrame("Loading weather...");
        weatherLoadPop.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        weatherLoadPop.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                weatherLoadPop.dispose();
            }
        ;
        });
        weatherLoadPop.setResizable(false);
        weatherLoadPop.setBounds(100, 50, 225, 100);
        JPanel weatherLoadPanel = new JPanel();
        weatherLoadPanel.setBackground(Color.RED);

        weatherLoadPanel.setPreferredSize(new Dimension(225, 100));
        JLabel weatherLoadLabel = new JLabel("Loading...0%");
        weatherLoadPanel.add(weatherLoadLabel);
        weatherLoadPop.add(weatherLoadPanel);
        weatherLoadPop.pack();
        weatherLoadPop.validate();
        weatherLoadPop.setVisible(true);
    }
}

我得到了:

Loading....

使用:

java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b20)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)