所以我有一个程序,当我单击按钮时会启动输入对话框。我需要帮助的是,一旦我从输入对话框中收集信息并且它们消失了,我按 Enter 键,输入对话框就会重新出现。为什么?
另外,如果输入对话框为空,我怎样才能得到它,它会显示为错误,然后重复直到它不为空?
<小时/>public static String fn;
public static String sn;
public void actionPerformed (ActionEvent e){
fn = JOptionPane.showInputDialog("What is your first name?");
sn = JOptionPane.showInputDialog("What is your second name");
//JOptionPane.showMessageDialog(null, "Welcome " + fn + " " + sn + ".", "", JOptionPane.INFORMATION_MESSAGE);
text.setText("Welcome " + fn + " " + sn + ".");
b.setVisible(false);
text.setVisible(true);
text.setBounds(140,0,220,20);
text.setHorizontalAlignment(JLabel.CENTER);
text.setEditable(false);
text.setBackground(Color.YELLOW);
writeToFile();
}
public BingoHelper(){
super("BINGO");
add(text);
text.setVisible(false);
add(b);
this.add(pnlButton);
pnlButton.setBackground(Color.BLUE);
//pnlButton.add(b);+
b.setVisible(true);
b.setBounds(145,145,145,20);
//b.setPreferredSize(new Dimension(150,40));
b.addActionListener(this);
b.setBackground(Color.GREEN);
rootPane.setDefaultButton(b);
}
最佳答案
当您调用rootPane.setDefaultButton
时,您指定的是由Enter键激活的按钮。
要防止 JOptionPane 在输入 Not Acceptable 时关闭,请创建一个实际的 JOptionPane 实例,然后创建您自己的按钮并将其指定为选项。按钮的 Action 或 ActionListener 必须调用 JOptionPane 的 setValue
方法:
final JOptionPane optionPane = new JOptionPane("What is your first name?",
JOptionPane.QUESTION_MESSAGE);
optionPane.setWantsInput(true);
Action accept = new AbstractAction("OK") {
private static final long serialVersionUID = 1;
public void actionPerformed(ActionEvent event) {
Object value = optionPane.getInputValue();
if (value != null && !value.toString().isEmpty()) {
// This dismisses the JOptionPane dialog.
optionPane.setValue(JOptionPane.OK_OPTION);
}
}
};
Object acceptButton = new JButton(accept);
optionPane.setOptions(new Object[] { acceptButton, "Cancel" });
optionPane.setInitialValue(acceptButton);
// Waits until dialog is dismissed.
optionPane.createDialog(null, "First Name").setVisible(true);
if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(optionPane.getValue())) {
// User canceled dialog.
return;
}
String fn = optionPane.getInputValue().toString();
关于java - 输入对话框[所需信息],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414844/