java 如何自动关闭 JOptionPane?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16632987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:31:14  来源:igfitidea点击:

How to close JOptionPane automatically?

javamultithreadingswingjoptionpane

提问by Ismail Sensei

I have a Threadrunning and in the time while the threadworking i want to display a JOptionPane.showMessageDialogsaying that the application is working and after thread is stopped, JOptionPanewill close automatically and OKbutton will be deactivated the whole time. My Main code :

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

And when i run it the JOptionPanedisplay but he won't close automatically unless i pressed OKbutton.

当我运行它时,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.");
}}

回答by MadProgrammer

  • Create your own Dialogwithout any buttons...make sure you set the defaultCloseOperationto DO_NOTHING
  • Use a ProgressMonitor
  • 创建你自己的Dialog没有任何按钮...确保你设置defaultCloseOperationDO_NOTHING
  • 用一个 ProgressMonitor

ProgressMonitor example...

进度监视器示例...

enter image description here

在此处输入图片说明

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;
        }
    }
}

Dialog Example

对话框示例

enter image description here

在此处输入图片说明

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;
        }
    }
}

回答by Sandro

 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);