如何在 Java 中调用 InputVerifier?

How to call an InputVerifier in Java?

我正在使用 NetBeans IDE 设计带有 java 和 swing 的图形用户界面。 GUI 的目的是获取用户输入,然后生成一些文本文件,用作用 Fortran 编写的程序的输入。

问题是 Fortran 程序无法处理文件名或路径中的空格。所以我需要检查用户的文件名在 GUI 中没有任何空格。

我已经实现了一个 InputVerifier ContainsNoSpaces 来执行此操作。但是,只有当用户关注 jTextField 时才会调用它。问题是用户不太可能关注 jTextField,而是使用激活 JFileChooser 的 jButton 输入文件名。

我想做的是在动作侦听器 jButton1ActionPerfromed 中放置类似 jTextField1.verifyInput() 的内容,以便我可以向用户显示错误对话框。我该怎么做?

这是一个最小的(不是)工作示例:

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;

public class InputVerifierMwe extends javax.swing.JFrame {

    public InputVerifierMwe() {
        initComponents();
    }

    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Choose file ...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setInputVerifier(new ContainsNoSpaces());

        jLabel1.setText("File name:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }                   

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        JFileChooser c = new JFileChooser();
        int rVal = c.showDialog(InputVerifierMwe.this, "Choose file");
        if (rVal == JFileChooser.APPROVE_OPTION) {
            jTextField1.setText(c.getSelectedFile().getName());

            /*
             *
             * This is where I need to verify the input.
             *
             */
        }
    }                                        

    class ContainsNoSpaces extends InputVerifier {
        public boolean verify(JComponent input) {

            final JTextComponent source = (JTextComponent) input;
            String s = source.getText();
            boolean valid = s.indexOf(" ") == -1;
            if (valid)
                return true;
            else {
                JOptionPane.showMessageDialog(source, "Spaces are not allowed.",
                        "Input error", JOptionPane.ERROR_MESSAGE);
                return false;
            }
        }
    }

    public static void main(String args[]) {
        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(InputVerifierMwe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(InputVerifierMwe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(InputVerifierMwe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InputVerifierMwe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new InputVerifierMwe().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;           
}

What I would like to do is place something like jTextField1.verifyInput() inside the action listener jButton1ActionPerfromed so that I can display an error dialog to the user. How can I do this?

如果用户可以选择在文本字段中手动输入文件名或使用文件选择器将文件默认输入文本字段,那么在 ActionListener 中您可以使用如下代码:

textField.setText(...);
textField.requestFocusInWindow();

所以现在在某些时候当文本字段失去焦点时需要验证文件名。

另一个选项是允许文件选择器只接受有效的文件名。您可以通过将编辑逻辑添加到文件选择器的 approveSelection(...) 方法来完成此操作,如以下所示:altering JFileChooser behaviour : preventing "choose" on enter in file path JTextField