【问题标题】:How to close JOptionPane automatically?如何自动关闭 JOptionPane?
【发布时间】:2013-05-14 00:50:42
【问题描述】:

我有一个Thread 正在运行,而在thread 工作时我想显示一个JOptionPane.showMessageDialog 表示应用程序正在工作并且在线程停止后,JOptionPane 将自动关闭并且OK按钮将一直停用。我的主要代码:

class Index {
public static void main(String args[]) {
   NewThread ob1 = new NewThread("One");
   NewThread ob2 = new NewThread("Two");
   NewThread ob3 = new NewThread("Three");
    System.out.println("Thread One is alive: "+ ob1.t.isAlive());
    System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
    System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
   while (ob1.t.isAlive()){
    JOptionPane.showMessageDialog(null,"Thread One is alive");
   }
    System.out.println("Thread One is alive: "+ ob1.t.isAlive());
    System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
    System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
    System.out.println("Main thread exiting.");
}}

当我运行它时,JOptionPane 显示,但除非我按下 OK 按钮,否则它不会自动关闭。

class NewThread implements Runnable {
String name; 
Thread t;
    NewThread(String threadname) {
        this.name = threadname;
        this.t = new Thread(this, name);
        System.out.println("New thread: " + t);
        this.t.start(); // Start the thread
    } 
public void run() {
    try {
    for(int i = 5; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(1000);
        }
        } catch (InterruptedException e) {
        System.out.println(name + " interrupted.");}
        System.out.println(name + " exiting.");
}}

【问题讨论】:

    标签: java multithreading swing joptionpane


    【解决方案1】:
    • 无需任何按钮即可创建您自己的Dialog...确保将defaultCloseOperation 设置为DO_NOTHING
    • 使用ProgressMonitor

    ProgressMonitor 示例...

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JFrame;
    import javax.swing.ProgressMonitor;
    import javax.swing.SwingWorker;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class TestProgress {
    
        public static void main(String[] args) {
            new TestProgress();
        }
    
        public TestProgress() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    new BackgroundWorker().execute();
    
                }
    
            });
        }
    
        public class BackgroundWorker extends SwingWorker<Void, Void> {
    
            private ProgressMonitor monitor;
    
            public BackgroundWorker() {
                addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
                            if (monitor == null) {
                                monitor = new ProgressMonitor(null, "Processing", null, 0, 99);
                            }
                            monitor.setProgress(getProgress());
                        }
                    }
    
                });
            }
    
            @Override
            protected void done() {
                if (monitor != null) {
                    monitor.close();
                }
            }
    
            @Override
            protected Void doInBackground() throws Exception {
                for (int index = 0; index < 100; index++) {
                    setProgress(index);
                    Thread.sleep(125);
                }
                return null;
            }
        }
    }
    

    对话框示例

    import java.awt.EventQueue;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class TestProgress {
    
        public static void main(String[] args) {
            new TestProgress();
        }
    
        public TestProgress() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    new BackgroundWorker().execute();
    
                }
    
            });
        }
    
        public class BackgroundWorker extends SwingWorker<Void, Void> {
    
            private JProgressBar pb;
            private JDialog dialog;
    
            public BackgroundWorker() {
                addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
                            if (dialog == null) {
                                dialog = new JDialog();
                                dialog.setTitle("Processing");
                                dialog.setLayout(new GridBagLayout());
                                dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                                GridBagConstraints gbc = new GridBagConstraints();
                                gbc.insets = new Insets(2, 2, 2, 2);
                                gbc.weightx = 1;
                                gbc.gridy = 0;
                                dialog.add(new JLabel("Processing..."), gbc);
                                pb = new JProgressBar();
                                gbc.gridy = 1;
                                dialog.add(pb, gbc);
                                dialog.pack();
                                dialog.setLocationRelativeTo(null);
                                dialog.setVisible(true);
                            }
                            pb.setValue(getProgress());
                        }
                    }
    
                });
            }
    
            @Override
            protected void done() {
                if (dialog != null) {
                    dialog.dispose();
                }
            }
    
            @Override
            protected Void doInBackground() throws Exception {
                for (int index = 0; index < 100; index++) {
                    setProgress(index);
                    Thread.sleep(125);
                }
                return null;
            }
        }
    }
    

    【讨论】:

    • 我是个初学者,我尝试制作自己的对话框,但我不知道如何设置选项窗格。有示例代码吗?
    • monitor = new ProgressMonitor(null, "Processing", null, 0, 99);void propertyChange(PropertyChangeEvent evt) 方法中取出不是更有意义吗? monitor 可以简单的在构造函数中初始化。
    • @c0der 如果从未调用过propertyChange 会发生什么?你会有一个悬空的引用......或者如果它被多次调用?对我来说,只在需要时使用才有意义,但如果你觉得换一种方式会更好,那可能没关系;)
    【解决方案2】:
     JOptionPane msg = new JOptionPane("Mensagem de advertência", JOptionPane.WARNING_MESSAGE);
        final JDialog dlg = msg.createDialog("Advertência");
        dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              Thread.sleep(5000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            dlg.setVisible(false);
          }
        }).start();
        dlg.setVisible(true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多