[英]Parsing JTextfield String into Integer
所以我有这个将String
从JTextField
转换为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)中) 之后解析数据是否更有意义?
所以我的建议有两个方面
NumberFormatException
。 如果发生异常,则可以通过调用setText()
清除JTextField,然后警告用户输入的数据无效,通常使用JOptionPane完成。 例如:
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.