在我的程序中,我想显示一个输入对话框以获取用户的输入。但如果用户未在特定时间内给出反馈,则输入对话框将关闭,并且将运行默认设置。
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class WorkerDemo {
public static void main(String[] args) {
JDialog.setDefaultLookAndFeelDecorated(true);
final JOptionPane Message = new JOptionPane("do u want to stop posting?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
final JDialog getInput = Message.createDialog("Select Yes or No");
final int Option = Message.PROPERTIES;
getInput.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
Message.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
//super.componentShown(e);
final Timer t = new Timer(5000,new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Message.setVisible(false);
}
});
t.start();
t.setRepeats(false);
}
});
Message.setVisible(true);
if (Option == JOptionPane.NO_OPTION) {
System.out.println("No button clicked");
} else if (Option == JOptionPane.YES_OPTION) {
System.out.println("Yes button clicked");
} else if (Option == JOptionPane.CLOSED_OPTION) {
System.out.println("JOptionPane closed");}
System.out.println("Outside code.");
}
}
这里的问题是如果条件不起作用。有没有办法解决这个问题。提前谢谢。
答案 0 :(得分:1)
以下是您的代码的工作版本:
import javax.swing.*;
public class WorkerDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JDialog.setDefaultLookAndFeelDecorated(true);
JOptionPane optionPane = new JOptionPane("do u want to stop posting?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
JDialog dialog = optionPane.createDialog("Select Yes or No");
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
Timer timer = new Timer(5000, e -> dialog.setVisible(false));
timer.setRepeats(false);
timer.start();
dialog.setVisible(true);
if (optionPane.getValue() instanceof Integer) {
int option = (Integer) optionPane.getValue();
if (option == JOptionPane.NO_OPTION) {
System.out.println("No button clicked");
}
else if (option == JOptionPane.YES_OPTION) {
System.out.println("Yes button clicked");
}
}
else {
System.out.println("dialog was closed by timer");
}
System.out.println("Outside code.");
});
}
}
解释和说明:
getValue()
方法获得的,该方法返回用户选择的内容。使用常量Message.PROPERTIES
初始化它的方法毫无意义。SwingUtilities.invoeLater()
。