【问题标题】:JOptionPane, closing and cancel not working while validating JTextFieldJOptionPane,在验证 JTextField 时关闭和取消不起作用
【发布时间】:2014-05-30 08:09:47
【问题描述】:

我有一个带有 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 语句。

欢迎任何建议!

【问题讨论】:

    标签: java swing dialog joptionpane


    【解决方案1】:

    实际上,如果您锁定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.
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用 '项目监听器'

      就像'ActionListener'。 if 语句应该在“ItemListener”中。这将检查项目并生成所需的弹出窗口“JOptionPane” 检查this。还有一件事;如果您说 ' ("go" 或 "ti"),您的 if 语句必须如下所示。'

      if(fn.getText().equals("") || !(go.isSelected()) || !(ti.isSelected())){
      

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 2013-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        相关资源
        最近更新 更多