且构网

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

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

更新时间:2022-11-07 23:38:13

我会回答这个问题:我不会为此目的使用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中显示表格数据,其中第1列和第2列可编辑但其他列不可编辑。

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

编辑

我不确定这是否是犹太洁食,但如果你进行计算,它可能会有用来自验证者。例如,更新为通用性:

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