所以我要将String
从JTextField
转换为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);
答案 0 :(得分:1)
您最大的问题是您在创建字段后立即解析文本字段内容,这没有任何意义。在允许用户有机会输入数据之后解析数据是否更有意义,最好是在某种类型的侦听器中,通常是ActionListener?
所以我的建议是双重的
NumberFormatException
的try / catch块中进行解析。如果发生异常,则通过调用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());
}
}
答案 1 :(得分:1)
来自docs:
抛出:NumberFormatException - 如果字符串不包含 可解析的整数。
空字符串""
不是可解析的整数,因此如果没有输入值,您的代码将始终生成NumberFormatException
。
有很多方法可以避免这种情况。您只需检查是否实际填充了String
的{{1}}值。您可以创建自定义amountField.getText()
,它只允许整数作为输入,但将Document添加到IntegerField
。创建一个只允许整数输入的文档:
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);
}
}
方法创建IntergerField
,如果未输入任何内容,则返回零:
getInt
现在,您无需进行任何检查即可从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