简体   繁体   中英

How to call an InputVerifier in Java?

I am using the NetBeans IDE to design a graphic user interface with java and swing. The purpose of the GUI is to take user input then generate some text files used as input for a program written in Fortran.

The problem is that the Fortran program cannot handle spaces in file names or paths. So I need to check that the user's file name does not have any spaces from within the GUI.

I have implemented an InputVerifier ContainsNoSpaces that does just this. However, it only gets called if the user focuses on the jTextField. The issue is that the user will not likely focus on the jTextField, instead entering the file name using the jButton that activates a JFileChooser.

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?

Here is a minimum (not) working example:

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?

If the user has the option to manually enter the filename in the text field or use a file chooser to default the file into the text field then in the ActionListener you could have code like:

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

So now at some point the file name will need to be verified when the text field loses focus.

Another option is to allow the file chooser to only accept valid file names. You can do this by adding your editing logic to the approveSelection(...) method of the file chooser as demonstrated in: altering JFileChooser behaviour : preventing "choose" on enter in file path JTextField

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM