java - 如何自动关闭JOptionPane?

标签 java multithreading swing joptionpane

我有一个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.");
}}

最佳答案

  • 不使用任何按钮创建自己的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;
            }
        }
    }
    

    关于java - 如何自动关闭JOptionPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632987/

    相关文章:

    java - 为什么包含 main 的类不必是 public 的?

    java - 有没有办法只将特定的 JPanel 区域标记为不透明?

    swift 4 : How to asynchronously use URLSessionDataTask but have the requests be in a timed queue?

    java - 在Java中,将线程的ID暴露给任意线程是否是一个安全问题?

    java - Eclipse主程序启动错误

    java - 使用 ClassLoader 加载源时 Apache Pdfbox 扁平化失败

    java - 我可以将方法存储在 Java 8 中的变量中吗?

    c# - 线程和垃圾收集

    java - JTree 实现

    java - 如何在 Swing 中使用图像放大和缩小调整滚动条