有了这个,
JOptionPane.showInputDialog(null,"Enter Your Name");
我希望用户输入对话框自动退出。我的意思是在 2 或 3 秒内仅显示 JOptionPane
用户输入对话框,然后关闭。它应该仅自动关闭该输入对话框,而不是整个程序。 System.exit(0)
方法导致整个程序退出,但我只想关闭该输入对话框而不是整个程序。然后我只想要 Swing 输入对话框而不是消息框和确认框。
最佳答案
如How to Make Dialogs所示,可以添加拦截Automatic Dialog Closing在 PropertyChangeListener
中。基于此example ,下面的变体将 label
、prompt
和 text
字段添加到选项 Pane 。 Swing Timer
从 TIME_OUT
开始倒计时,每次都会更新 label
。当按下 OK 按钮或时间耗尽时,PropertyChangeListener
会调度 WINDOW_CLOSING
事件。
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.Timer;
/**
* @see https://stackoverflow.com/a/44417958/230513
* @see https://stackoverflow.com/a/12451673/230513
*/
public class JOptionTimeTest implements ActionListener, PropertyChangeListener {
private static final int TIME_OUT = 10;
private int count = TIME_OUT;
private final Timer timer = new Timer(1000, this);
private final JDialog dialog = new JDialog();
private final JOptionPane optPane = new JOptionPane();
private final JLabel label = new JLabel(message());
private final JLabel prompt = new JLabel("Enter Your Name:");
private final JTextField text = new JTextField("Name");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new JOptionTimeTest().createGUI();
}
});
}
private void createGUI() {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
timer.setCoalesce(false);
text.selectAll();
Object[] array = {label, prompt, text};
optPane.setMessage(array);
optPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
optPane.setOptionType(JOptionPane.DEFAULT_OPTION);
optPane.addPropertyChangeListener(this);
dialog.add(optPane);
dialog.pack();
frame.add(new JLabel(frame.getTitle(), JLabel.CENTER));
frame.pack();
frame.setVisible(true);
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
timer.start();
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (JOptionPane.VALUE_PROPERTY.equals(prop)) {
thatsAllFolks();
}
}
public void actionPerformed(ActionEvent e) {
count--;
label.setText(message());
if (count == 0) {
thatsAllFolks();
}
timer.restart();
}
private String message() {
return "Closing in " + count + " seconds.";
}
private void thatsAllFolks() {
dialog.setVisible(false);
dialog.dispatchEvent(new WindowEvent(
dialog, WindowEvent.WINDOW_CLOSING));
}
}
关于java - JOptionPane.showInputDialog自动退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44404901/