有了这个,
JOptionPane.showInputDialog(null,"Enter Your Name");
我希望用户输入对话框自动退出。我的意思是在2或3秒内只显示JOptionPane
用户输入对话框并在此之后关闭。它应该只自动关闭该输入对话框,而不是整个程序。 System.exit(0)
方法导致完整程序退出,但我只想关闭该输入对话框而不是完整程序。然后我只想要Swing输入对话框而不是消息框和确认框。
答案 0 :(得分:2)
如How to Make Dialogs所示,您可以在PropertyChangeListener
中添加拦截Automatic Dialog Closing。根据此example,下面的变体会在选项窗格中添加label
,prompt
和text
字段。 Swing Timer
从TIME_OUT
倒计时,每次更新label
。当按下确定按钮或时间用完时,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));
}
}