java SwingWorker对话框未显示

时间:2017-04-21 07:52:00

标签: java swing jframe swingworker

在Netbeans中,我创建了一个GUI项目,它使用框架前端,我可以添加组件并双击编辑他们的事件。我指的是具有“源”,“设计”和“历史”标签的窗口。

以下是组件和关系:

1-打开文件选择器的按钮。

2- TextArea显示文件选择器的结果。如果用户选择文件,它将在TextArea中显示文件名;否则会写“由用户取消”。

3-同时,如果用户选择了一个文件,我想打开一个“请稍候”对话框SwingWorker并在后台进行一些工作。

问题是,当用户选择文件时,我没有看到请等待对话框! Netbeans生成的完整代码可在pastebin获得。部分代码如下所示:

private void OpenSongFileActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here:
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setAcceptAllFileFilterUsed(false);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3 files", "mp3");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
    int result = fileChooser.showOpenDialog(this);
    if (result != JFileChooser.APPROVE_OPTION) {
        //ReadInfo.setText("No song has been selected");
        System.out.println("OpenSongFile canceled by user");
        return;
    }
    final JDialog loading = new JDialog(this);
    JPanel p1 = new JPanel(new BorderLayout());
    p1.add(new JLabel("Please wait..."), BorderLayout.CENTER);
    loading.setUndecorated(true);
    loading.getContentPane().add(p1);
    loading.pack();
    loading.setLocationRelativeTo(this);
    loading.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    loading.setModal(true);
    SwingWorker<String, Void> worker = new SwingWorker<String, Void>() {
        @Override
        protected String doInBackground() throws InterruptedException {
            for (int i = 0; i < 10000; i++) 
                for (int j = 0; j < 10000; j++) 
                    ;
            return "hello";
        }
        @Override
        protected void done() {
            loading.dispose();
        }
    };
    worker.execute();
    loading.setVisible(true);
    try {
        worker.get();
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    File selectedFile = fileChooser.getSelectedFile();
    ReadInfo.setText("Selected file: " + selectedFile.getAbsolutePath());
}                              

P.S:我使用了解释here的SwingWorker代码。

1 个答案:

答案 0 :(得分:1)

worker.get();会一直阻止,直到SwingWorker返回,这意味着你阻止了EDT,阻止了对话框的显示。

相反,请使用SwingWorker PropertyChangeListener支持并监控STARTDONE事件

SwingWorker<String, Void> worker = new SwingWorker<String, Void>() {
    @Override
    protected String doInBackground() throws InterruptedException {
        Thread.sleep(5000);
        return "hello";
    }

    @Override
    protected void done() {
        loading.dispose();
    }
};
worker.addPropertyChangeListener(new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println(evt.getPropertyName());
        Object value = evt.getNewValue();
        if (value instanceof SwingWorker.StateValue) {
            SwingWorker.StateValue state = (SwingWorker.StateValue) value;
            switch (state) {
                case DONE: {
                    try {
                        String result = worker.get();
                        JOptionPane.showMessageDialog(null, result);
                    } catch (InterruptedException | ExecutionException ex) {
                        ex.printStackTrace();
                    }
                }
                break;
            }
        }
    }
});
worker.execute();
loading.setVisible(true);

另一个问题是你的循环可能运行得如此之快,以至于窗口在屏幕上实现之前已经关闭。

例如,我只是使用Thread.sleep暂停doInBackground方法5秒......

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class Memory extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                makeItSo();
            }
        });
    }

    public static void makeItSo() {
        final JDialog loading = new JDialog();
        JPanel p1 = new JPanel(new BorderLayout());
        p1.add(new JLabel("Please wait..."), BorderLayout.CENTER);
        loading.setUndecorated(true);
        loading.getContentPane().add(p1);
        loading.pack();
        loading.setLocationRelativeTo(null);
        loading.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        loading.setModal(true);
        SwingWorker<String, Void> worker = new SwingWorker<String, Void>() {
            @Override
            protected String doInBackground() throws InterruptedException {
                Thread.sleep(5000);
                return "hello";
            }

            @Override
            protected void done() {
                loading.dispose();
            }
        };
        worker.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                System.out.println(evt.getPropertyName());
                Object value = evt.getNewValue();
                if (value instanceof SwingWorker.StateValue) {
                    SwingWorker.StateValue state = (SwingWorker.StateValue) value;
                    switch (state) {
                        case DONE: {
                            try {
                                String result = worker.get();
                                JOptionPane.showMessageDialog(null, result);
                            } catch (InterruptedException | ExecutionException ex) {
                                ex.printStackTrace();
                            }
                        }
                        break;
                    }
                }
            }
        });
        worker.execute();
        loading.setVisible(true);
    }

}