【问题标题】:How to restore InputVerifier mechanism while using cancel button?使用取消按钮时如何恢复 InputVerifier 机制?
【发布时间】:2018-04-21 13:59:39
【问题描述】:

我在 JFormattedTextField 上有一个 InputVerifier。当场完全失去焦点时调用它。我添加了一个取消按钮(JButton),但不想在单击此按钮时调用 InputVerifier。

当焦点在字段上丢失时调用MyVerifier,没有任何问题。但是,在我单击 clearButton 后,不会再次调用 InputVerifier,就好像即使没有单击按钮一样。

完整代码为:

public class DemoFrame extends javax.swing.JFrame {

    /** Creates new form DemoFrame */
    public DemoFrame() {
        initComponents();
        name.setValue("");
        name.setInputVerifier(new MyVerifier());
        clear.setVerifyInputWhenFocusTarget(false);
    }

    private class MyVerifier extends javax.swing.InputVerifier {
     public boolean verify(javax.swing.JComponent input) {
         System.out.println("Field is being verified");
          return true;
      }
      public boolean shouldYieldFocus(javax.swing.JComponent input) {
          return verify(input);
      }
  }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        name = new javax.swing.JFormattedTextField();
        clear = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        name.setText(" ");

        clear.setText("clear");
        clear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(231, Short.MAX_VALUE)
                .addComponent(clear)
                .addGap(112, 112, 112))
            .addGroup(layout.createSequentialGroup()
                .addGap(116, 116, 116)
                .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(156, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(94, 94, 94)
                .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
                .addComponent(clear)
                .addGap(73, 73, 73))
        );

        pack();
    }// </editor-fold>

    private void clearActionPerformed(java.awt.event.ActionEvent evt) {
        name.setValue(null);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DemoFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton clear;
    private javax.swing.JFormattedTextField name;
    // End of variables declaration
}

如果字段失去焦点而没有单击按钮,为什么不调用 InputVerifier?

【问题讨论】:

  • 张贴minimal reproducible example 说明问题。您的“清除”按钮必须执行一些导致问题的代码。
  • 好的,我包含了整个代码。
  • 如果我在 Verified 字段和 JButton 之间添加另一个 JFormattedTextField,问题就会消失。我想验证字段没有被验证,因为按钮获得焦点。我想解决方法是包括一个可聚焦的虚拟字段。有更好的解决方案吗?
  • 据我所知,InputVerifier 没有被调用,因为您告诉 API 不要调用它,而是将setVerifyInputWhenFocusTarget 设置为false。这意味着当该字段具有焦点然后焦点移动到clear 按钮时,InputVerifier 根本不会被调用
  • 我想我应该将问题更改为,当单击取消按钮等按钮失去焦点时,如何避免验证字段?

标签: java swing inputverifier


【解决方案1】:

嗯。我找到了解决方案。

    clear.setFocusable(false);

这样就解决了问题。

【讨论】:

  • 这不是一个很好的解决方案,因为现在用户无法通过键盘导航到按钮
  • 也许吧。但是为什么要导航到取消按钮呢?用户将能够导航到除取消按钮之外的其他字段或组件。这似乎不无道理。此外,无法提供其他简单的解决方案。
  • 对于依赖屏幕阅读器的用户来说,这是个问题,因为他们不会用鼠标导航,而是用键盘导航。高级用户通常不使用鼠标,他们使用键盘导航。我知道这会惹恼我的废话。就个人而言,我不喜欢 InputVerifier 限制焦点,因为用户以违反显示顺序的方式输入值是完全合理的,相反,知道他们必须改变他们的思维方式和专注于开发人员决定的顺序,我更喜欢视觉标记字段和验证后的组合
  • 我理解并同意。但是,我需要验证的字段是 dababase 键。因此,如果用户更改此字段,我需要重新加载整个表单。因此,验证用户输入是批评者。我可以添加一个 propertyChangeListener,但我不知道用户是否更改了值或应用程序(例如当按钮清除表单时)。
  • 所以...跳起来打我耳光的是...“确定”或“接受”按钮在哪里?您提出的基本问题是只有两个组件,这并不完全有意义,因为它们具有“忽略”该值的能力,它们如何“接受”它?第三个组件将解决问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2018-01-25
  • 2020-04-02
  • 1970-01-01
相关资源
最近更新 更多