我有一个带有 JTextField 的 JOptionPane:
private void imageFilePanel(){
JRadioButton go = new JRadioButton("Grid Object");
JRadioButton ti = new JRadioButton("Tile Image");
JTextField fn = new JTextField(15);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(fn);
panel.add(go);
panel.add(ti);
JOptionPane.showOptionDialog(null, panel, "Name Image", JOptionPane.CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if(fn.getText().equals("") || !(go.isSelected()) && !(ti.isSelected())){
JOptionPane.showMessageDialog(frame, "Complete required fields.", "Error Message", JOptionPane.ERROR_MESSAGE);
imageFilePanel();
}
}
我不希望用户继续下一步,除非他们填写 JTextField“fn”并选择 JRadioButtons 之一(“go”或“ti”)。
但是,当用户单击窗口关闭或取消按钮时,我的代码现在会执行 if 语句。这不是我想要的行为;我希望仅当用户尝试按“确定”按钮而不填写“fn”、不选择“go”或“ti”或两者都不选择时才评估 if 语句。
欢迎任何建议!
最佳答案
实际上,如果您锁定在 showOptionDialog
处,您会看到它返回一个 int
,其中包含在对话框中按下的按钮,因此您可以使用该 int
变量来确定天气是否执行您的语句。
例如:
int result = JOptionPane.showOptionDialog(null, panel, "Name Image", JOptionPane.CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if(result == JOptionPane.YES_OPTION) {
//your code.
}
关于java - JOptionPane,验证 JTextField 时关闭和取消不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23092741/