简体   繁体   English

如何在Java中调用InputVerifier?

[英]How to call an InputVerifier in Java?

I am using the NetBeans IDE to design a graphic user interface with java and swing. 我正在使用NetBeans IDE用Java和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. GUI的目的是获取用户输入,然后生成一些文本文件,用作用Fortran编写的程序的输入。

The problem is that the Fortran program cannot handle spaces in file names or paths. 问题在于,Fortran程序无法处理文件名或路径中的空格。 So I need to check that the user's file name does not have any spaces from within the GUI. 因此,我需要检查用户的文件名在GUI中是否没有空格。

I have implemented an InputVerifier ContainsNoSpaces that does just this. 我已经实现了一个InputVerifier ContainsNoSpaces来做到这一点。 However, it only gets called if the user focuses on the jTextField. 但是,只有在用户专注于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. 问题是用户不太可能关注jTextField,而是使用激活JFileChooser的jButton输入文件名。

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. 我想做的是在动作监听器jButton1ActionPerfromed内放置类似jTextField1.verifyInput()之类的东西,以便向用户显示错误对话框。 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. 我想做的是在动作监听器jButton1ActionPerfromed内放置类似jTextField1.verifyInput()之类的东西,以便向用户显示错误对话框。 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: 如果用户可以选择在文本字段中手动输入文件名,或使用文件选择器将文件默认设置为文本字段,则在ActionListener中,您可以使用以下代码:

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 您可以通过将编辑逻辑添加到文件选择器的approveSelection(...)方法来实现此目的,如以下所示: 更改JFileChooser行为:防止在输入文件路径JTextField时“选择”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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