JPanel直到代码之后才显示

Ang*_*own 1 java swing jpanel event-dispatch-thread

我想要做的是在进程发生时显示带有进度条的新面板.

我的代码如下:

case "GoButton":
    cards.show(this, "pp");
    this.test();
    cards.show(this, "panel1");
    break;
Run Code Online (Sandbox Code Playgroud)

这是一种actionPerformed方法

但是当我运行程序时它只是忽略第一个cards.show,它执行test代码然后执行第二个cards.show

如果您需要,我还会为您提供其余的代码

public CreatePanel(JFrame frame) {
        ext = new ArrayList<>();
        files = new ArrayList<>();

        this.mainWindow = frame;
        this.setSize(256, 256);
        cards = new CardLayout();
        this.setLayout(cards);

        panel1 = new JPanel(null);
        createPanel1(panel1);
        this.add(panel1, "panel1");

        panel2 = new JPanel(null);
        createPanel2(panel2);
        this.add(panel2, "panel2");

        panel3 = new JPanel(null);
        createPanel3(panel3);
        this.add(panel3, "pp");

        cards.show(this, "panel1");
    }

public class ProgressPanel {
    private static JPanel panel;
    private static JProgressBar progressBar;
    private static int progress;

    public static JPanel createProgressPanel(){
        ProgressPanel.panel = new JPanel(null);
        ProgressPanel.initPanel();
        return ProgressPanel.panel;
    }

    private static void initPanel(){
        panel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(progress);
        progressBar.setStringPainted(true);
        panel.add(progressBar, c);
    }

    public static void updateProgress(int x){
        ProgressPanel.progress += x;
    }

    public void resetProgress(){
        this.progress = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

你的问题可能喜欢这里:this.test();.我打赌这个方法调用长时间运行的代码,并且由于它是在Swing事件线程上调用的,它正在占用这个线程,阻止你的GUI自我更新,实际上完全冻结了GUI.解决方案:使用SwingWorker或其他后台线程进行长时间运行的任务.请看一下Swing中的Concurrency.

请注意,如果您使用SwingWorker,则需要使用PropertyChangeListener或done()在后台线程完成时通知的方法以及是时候调用cards.show(this, "panel1");.我自己,我将一个PropertyChangeListener添加到我的SwingWorker,因为这样,我既可以监听监听器的完成,也可以监听worker的progress属性的变化,然后使用该值设置我的JProgressBar的值.