且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DocumentListener Java,如何防止 JTextBox 中出现空字符串?

更新时间:2022-11-07 23:33:20

我会回答这个问题:我不会将 DocumentListener 用于此目的,因为在我看来这不是该工作的错误工具.一方面,当用户仍在将数据(尚未完成的数据)输入 JTextField 时,它会持续侦听和更新结果.使用添加到 JButton 或 JTextFields 的 ActionListener 会更好.

I'll make this an answer: I wouldn't use a DocumentListener for this purpose as it seems to me the wrong tool for the job. For one, it is continually listening and updating the results while the user is still entering data, data that is as yet incomplete, into the JTextField. Much better would be to use an ActionListener added to a JButton or to your JTextFields.

我想你可以使用 FocusListener,但即使这样我也担心,因为它是相当低级的.

I suppose you could use a FocusListener, but even that concerns me since it is quite low-level.

另外:考虑使用 InputVerifier 来验证您的输入.

Also: consider using an InputVerifier to validate your input.

另外:考虑在 JTable 中显示表格数据,其中第一列和第二列可编辑,但其他列不可编辑.

Also: consider displaying your tabular data in a JTable where the 1st and 2nd columns are editable but the others are not.

编辑
我不确定这是否符合 kosher 标准,但如果您在验证器中进行计算,它可能会起作用.例如,更新为一般性:

Edit
I'm not sure if this is kosher, but it could work if you do your calculation from within the verifier. For example, updated for generality:

import javax.swing.*;

/**
* @see http://***.com/a/11818183/522444
*/
public class VerifierEg {

    private static final String ZERO = "0.0";
    private JTextField field1 = new JTextField(ZERO, 5);
    private JTextField field2 = new JTextField(ZERO, 5);
    private JTextField resultField = new JTextField(ZERO, 10);

    private void createAndShowGui() {
        resultField.setEditable(false);
        resultField.setFocusable(false);

        JPanel mainPanel = new JPanel();
        final JTextField[] fields = {field1, field2};

        mainPanel.add(field1);
        mainPanel.add(new JLabel(" x "));
        mainPanel.add(field2);
        mainPanel.add(new JLabel(" = "));
        mainPanel.add(resultField);

        for (JTextField field : fields) {
            field.setInputVerifier(new MyInputVerifier(field));
        }

        JFrame frame = new JFrame("VerifierEg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void calcProduct() {
        double d1 = Double.parseDouble(field1.getText());
        double d2 = Double.parseDouble(field2.getText());
        double prod = d1 * d2;
        resultField.setText(String.valueOf(prod));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                VerifierEg eg = new VerifierEg();
                eg.createAndShowGui();
            }
        });
    }

    /**
    * @see http://***.com/a/11818946/230513
    */
    private class MyInputVerifier extends InputVerifier {

        private JTextField field;
        private double value;

        public MyInputVerifier(JTextField field) {
            this.field = field;
        }

        @Override
        public boolean shouldYieldFocus(JComponent input) {
            if (verify(input)) {
                field.setText(String.valueOf(value));
                calcProduct();
                return true;
            } else {
                field.setText(ZERO);
                field.selectAll();
                return false;
            }

        }

        @Override
        public boolean verify(JComponent input) {
            try {
                value = Double.parseDouble(field.getText());
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
    }
}