如何在Java中调用InputVerifier?

时间:2015-10-20 21:42:28

标签: java swing inputverifier

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

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

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

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

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

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;           
}

1 个答案:

答案 0 :(得分:3)

  

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

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

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

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

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