即使被动作事件调用,如何让 JFrame 显示 JPanel 文本内容?

问题描述 投票:0回答:1

我有一个简单的 JFrame 对话框,当主程序完成其他活动时,应该显示“请稍候”消息:

public JFrame waitDialog() {
         JFrame wait = new JFrame();
         wait.setTitle("My Dialog");
         wait.setAlwaysOnTop(true); 
         wait.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
         wait.setSize(300, 150);
         wait.setLocationRelativeTo(null);  
         wait.setLayout(new BorderLayout());
         String msg = "Plase Wait...";
         wait.add(new JLabel(msg), BorderLayout.CENTER);
         return wait;
    }

当我在程序流程中调用它时,它工作正常:

     ...
     JFrame wait = waitDialog();
     wait.setVisisble(true);
     for (int i=0;i<1000;i++){
         // Other activities
         System.out.println(i);
     }
     wait.setVisisble(false);
     ...

但是,如果我通过 ActionEvent 执行此对话框(我单击主应用程序 JFrame 上的“执行其他活动”按钮),即使我使用完全相同的代码来调用 waitDialog(),该对话框也不会显示任何文本。它显示一个空对话框,没有“请稍候...”消息

     public void actionPerformed(ActionEvent action){
     if (action.getSource==waitforit) {
         runWait(); 
     }

     Public void runWait() {
        JFrame wait = waitDialog();
     wait.setVisisble(true);
     for (int i=0;i<1000;i++){
         // Other activities
         System.out.println(i);
     }
     wait.setVisisble(false);
         }

我对此进行了广泛的修改,并且无法理解为什么 JPanel 文本仅在我通过 ActionEvent 调用对话框时才无法显示。

我在这里缺少什么?

java jframe jlabel actionevent
1个回答
0
投票

操作(例如按下按钮)由特殊线程 AWT-EventQueue 执行。负责绘制整个框架的同一线程。如果您允许该函数完成 JFrame 的绘制并在另一个线程延迟后关闭它,您的代码应该可以工作。

button.addActionListener((l) -> {
    JFrame wait = waitDialog();
    wait.setVisible(true);
    closeFrameDelayed(wait);
});
static void closeFrameDelayed(JFrame frame) {
    new Thread(() -> {
        try {
            Thread.sleep(2000); // Wait 2 seconds
        } catch (InterruptedException ex) {
            // No error handling (or printing) is bad error handling,
            // but that is out of scope here, i guess
            ex.printStackTrace(System.out);
        } finally {
            // SwingUtilities.invokeLater pushes the comand to the AWT-EventQueue
            // This is required, because AWT/Swing methods are not thread safe
            SwingUtilities.invokeLater(() -> {
                frame.setVisible(false);
            });
        }
    }).start();
}

话虽这么说,生成多个框架通常不是一个好主意(请参阅多个 JFrame 的使用:好还是坏实践?)。最好改用 JDialog。

© www.soinside.com 2019 - 2024. All rights reserved.