繁体   English   中英

将JTextfield字符串解析为整数

[英]Parsing JTextfield String into Integer

所以我有这个将StringJTextField转换为int Exception in thread "main" java.lang.NumberFormatException: For input string: ""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);

最大的问题是创建字段后立即解析文本字段的内容,这没有任何意义。 允许用户有机会输入数据(最好是在某种类型的侦听器(通常是ActionListener)中) 之后解析数据是否更有意义?

所以我的建议有两个方面

  1. 不要尝试在创建JTextField时立即提取数据,而要在适当的侦听器中提取数据。 该类型只能为您所知,但通常我们会使用ActionListeners进行此类操作,以便我们可以在用户按下JButton时进行解析。
  2. 在try / catch块中进行解析,并在其中捕获NumberFormatException 如果发生异常,则可以通过调用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());
    }
}

文档

抛出:NumberFormatException-如果字符串不包含可分析的整数。

空的字符串""不是可解析的整数,因此,如果未输入任何值,您的代码将始终产生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 ,如果不输入任何内容,该方法将返回零:

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM