将 JTextfield 字符串解析为整数

Parsing JTextfield String into Integer

所以我需要将 StringJTextField 转换为 int。它说 Exception in thread "main" java.lang.NumberFormatException: For input string: ""。请帮忙。

 JTextField amountfld = new JTextField(15);
 gbc.gridx = 1; // Probably not affecting anything
 gbc.gridy = 3; //
 add(amountfld, gbc);
 String amountString = amountfld.getText();
 int amount = Integer.parseInt(amountString);

您最大的问题是您在创建字段后立即解析文本字段内容,这是没有意义的。在 after 之后解析数据是否更有意义,让用户有机会输入数据,最好是在某种监听器中,通常是 ActionListener?

所以我的建议有两个

  1. 不要尝试在创建 JTextField 时立即提取数据,而是在适当的侦听器中进行提取。该类型只能为您所知,但我们经常将 ActionListeners 用于此类事情,以便我们可以在用户按下 JButton 时进行解析。
  2. 在捕获 NumberFormatException 的 try / catch 块中进行解析。如果发生异常,您然后通过调用 setText() 清除 JTextField,然后警告用户他们正在输入无效数据,通常使用 JOptionPane 来完成。
  3. 好吧,第三条建议:如果可能,尝试通过 1) 给用户一个默认值,以及 2) 甚至不允许用户输入无效数据,使您的 GUI 完全防白痴。 JSlicer 或 JSpinner 或 JComobBox 可以很好地解决这个问题,因为它们会限制允许的输入。

例如:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class GetNumericData extends JPanel {
    private JTextField amountfld = new JTextField(15);
    private JSpinner amountSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 40, 1));
    private JButton submitButton = new JButton(new SubmitAction("Submit"));
    private JButton exitButton = new JButton(new ExitAction("Exit", KeyEvent.VK_X));

    public GetNumericData() {
        add(new JLabel("Amount 1:"));
        add(amountfld);
        add(new JLabel("Amount 2:  $"));
        add(amountSpinner);
        add(submitButton);
        add(exitButton);
    }

    // do all your parsing within a listener such as this ActionListener
    private class SubmitAction extends AbstractAction {
        public SubmitAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String amountTxt = amountfld.getText().trim();
            try {
                int amount1 = Integer.parseInt(amountTxt);
                // if this parse fails we go immediately to the catch block

                int amount2 = (Integer) amountSpinner.getValue();
                String message = String.format("Your two amounts are %d and %d", amount1, amount2);
                String title = "Amounts";
                int messageType = JOptionPane.INFORMATION_MESSAGE;
                JOptionPane.showMessageDialog(GetNumericData.this, message, title, messageType);

            } catch (NumberFormatException e1) {
                String message = "You can only enter numeric data within the amount field";
                String title = "Invalid Data Entered";
                int messageType = JOptionPane.ERROR_MESSAGE;
                JOptionPane.showMessageDialog(GetNumericData.this, message, title, messageType);
                amountfld.setText("");
            }
        }
    }

    private class ExitAction extends AbstractAction {

        public ExitAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Get Data");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new GetNumericData());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

来自 docs:

Throws: NumberFormatException - if the string does not contain a parsable integer.

空字符串 "" 不是可解析的整数,因此如果未输入任何值,您的代码将始终生成 NumberFormatException

您可以通过多种方式避免这种情况。您可以简单地检查您从 amountField.getText() 获得的 String 值是否实际填充。您可以创建自定义 IntegerField,它只允许输入整数,但将 Document 添加到 JTextField。创建一个文档以仅允许输入整数:

public static class IntegerDocument extends PlainDocument {

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        StringBuilder sb = new StringBuilder(str.length());
        for (char c:str.toCharArray()) {
            if (!Character.isDigit(c)) {
                sb.append(c);
            }
        }
        super.insertString(offs, sb.toString(), a);
    }
}

现在用方便的 getInt 方法创建 IntergerField,如果未输入任何内容,returns 零:

public static class IntegerField extends JTextField {
    public IntegerField(String txt) {
        super(txt);
        setDocument(new IntegerDocument());
    }

    public int getInt() {
        return this.getText().equals("") ? 0 : Integer.parseInt(this.getText());        
    }
}

现在您可以从 amountField 中检索整数值而无需进行任何检查:

JTextField amountField = new IntegerField("15");
...
//amount will be zero if nothing is entered
int amount = amountField.getInt();