2

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

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

我已经实现了一个 InputVerifierContainsNoSpaces就是这样做的。但是,只有当用户关注 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;           
}
4

1 回答 1

3

我想做的是在动作监听器 jButton1ActionPerfromed 中放置类似 jTextField1.verifyInput() 的东西,这样我就可以向用户显示一个错误对话框。我怎样才能做到这一点?

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

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

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

另一种选择是允许文件选择器只接受有效的文件名。您可以通过将编辑逻辑添加到approveSelection(...)文件选择器的方法中来做到这一点,如下所示:改变 JFileChooser 行为:防止在文件路径 JTextField 中输入时“选择”

于 2015-10-20T21:53:49.620 回答