尝试仅允许将数字输入JTextField,将非数字设置为0

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试仅允许将数字输入JTextField,将非数字设置为0相关的知识,希望对你有一定的参考价值。

有麻烦的人这是我的华氏温度转换器类,我似乎无法让我的代码识别以下,这确保只有数字输入文本字段,如果没有,设置为0:

try {
            Double.parseDouble(fahr.getText());
        } catch (NumberFormatException e) {
            fahr.setText("0");
        }

我认为这是因为它在我班级中的位置。请查看我的全班(我把它放在代码的底部):

public class Temperature implements ActionListener  {

    private static JTextField fahr;
    private static JTextField cels;
    private JFrame frame;
    private JButton first;
    private JButton second;
    private double fahrVal;
    private Double fahrConv;
    private double celsVal;
    private double celsConv;
    private NumberFormat amountFormat;


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Temperature window = new Temperature();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Temperature() {
        initialize();
        first.addActionListener((ActionListener) this);
        second.addActionListener((ActionListener) this);
    }

    private void initialize() { 
        amountFormat = NumberFormat.getNumberInstance();
        frame = new JFrame("raB eltiT");
        frame.setBounds(100, 50, 350, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        first = new JButton("...To Celsius");
        first.setBounds(130, 60, 100, 50);
        first.setBackground(Color.cyan);
        first.setActionCommand("click");
        first.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JButton src = (JButton) ae.getSource();
                //System.out.println("Button labeled " + src.getText() + " was clicked");
            }
        });
        first.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent me) {
                 cels.setText(String.valueOf(fahrConv));
            }
        });


        frame.getContentPane().add(first);

        second = new JButton("...To Fahrenheit");
        second.setBounds(130, 230, 100, 50);
        second.setBackground(Color.pink);
        second.setActionCommand("instead");
        frame.getContentPane().add(second);
        second.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent me) {
                 fahr.setText(String.valueOf(celsConv));
            }
        });

        // Build the Fahrenheit side

        JLabel fLabel = new JLabel("Fahrenheit");
        fahr = new JTextField("32");
        fahr.setPreferredSize(new Dimension(50,50));
        fahr.setHorizontalAlignment(JTextField.CENTER);
        JPanel fPanel = new JPanel();
        fPanel.setBounds(40, 120,100,100);
        fPanel.add(fLabel);
        fPanel.add(fahr);
        frame.getContentPane().add(fPanel);


        JLabel cLabel = new JLabel("Celsius");
        cels = new JTextField("0");
        cels.setPreferredSize(new Dimension(50,50));
        cels.setHorizontalAlignment(JTextField.CENTER);
        JPanel cPanel = new JPanel();
        cPanel.setBounds(220, 120, 100,100);
        cPanel.add(cLabel);
        cPanel.add(cels);
        frame.getContentPane().add(cPanel); 


        // Put it all up on the screen

        frame.setVisible(true);  

        try {// if is number
            Double.parseDouble(fahr.getText());
        } catch (NumberFormatException e) {
            fahr.setText("0");
        }
    }
    public void actionPerformed(ActionEvent event) {
         String fahrText = fahr.getText();
         fahrVal = Double.parseDouble(fahrText);
         fahrConv = ((fahrVal - 32)*5)/9;
         fahrConv = Double.parseDouble(new DecimalFormat("##.#").format(fahrConv));

        String celsText = cels.getText();
        celsVal = Double.parseDouble(celsText);
        celsConv = 32 + (celsVal * 9 / 5);
        celsConv = Double.parseDouble(new DecimalFormat("##.#").format(celsConv));


    }
}
答案

问题不在于你在做什么,而在于你在做什么的时候和地点。你在打电话

try {// if is number
    Double.parseDouble(fahr.getText());
} catch (NumberFormatException e) {
    fahr.setText("0");
}

在您创建GUI的代码中,然后在用户有机会将数据输入JTextField之前发生这种情况,这使得此代码无用。更好的解决方案是将此代码放入一个侦听器,该侦听器在用户准备好提交数据时响应,例如在ActionListener的开头 - 然后调用return:

就像是:

public void actionPerformed(ActionEvent event) {
    try {
        Double.parseDouble(fahr.getText());
    } catch (NumberFormatException e) {
        fahr.setText("0");
        // display a JOptionPane error message so the user knows there's been a problem
        return; // so the code below isn't called if input in error
    }
    String fahrText = fahr.getText();
    fahrVal = Double.parseDouble(fahrText);
    fahrConv = ((fahrVal - 32)*5)/9;
    fahrConv = Double.parseDouble(new DecimalFormat("##.#").format(fahrConv));

    String celsText = cels.getText();
    celsVal = Double.parseDouble(celsText);
    celsConv = 32 + (celsVal * 9 / 5);
    celsConv = Double.parseDouble(new DecimalFormat("##.#").format(celsConv));
}

其他选择:

  • 使用JFormattedTextField
  • 或者使用JSpinner
  • 或者使用DocumentListener

其他无关的问题:

  • 不要将MouseListeners添加到JButton,而是使用ActionListeners。否则,听众将无法正常行事。例如,如果按钮已被禁用,MouseListener仍将响应,而ActionListener将在这种情况下正确响应。
  • 避免使用空布局和绝对定位,因为这会导致严格的GUI难以增强,调试并且在一个平台上看起来很好,而在所有其他平台上看起来很糟糕。

以上是关于尝试仅允许将数字输入JTextField,将非数字设置为0的主要内容,如果未能解决你的问题,请参考以下文章

Oracle Apex:如何将表单中的数字字段限制为仅允许数字?

实时输入文本过滤,仅允许数字

JTextField需要两倍的输入,但为什么呢?

仅允许onKeyPress或onKeyDown中的React中的数字

数字仅输入数字[重复]

Select2.js - 搜索输入以仅允许数字