NumberFormatException方法

时间:2013-12-09 02:32:26

标签: java swing awt numberformatexception

大家好,我想请别人帮帮我。我想在同一个类中编写一个方法来使用NumberFormatException来获取JTextField的值并检查它是否为数字并打印。另外,如何在actionPerformed方法中实现此代码?

这是主要方法

public class main {
    public static void main(String args[]){
        JavaApplication19 is = new JavaApplication19("title");
        is.setVisible(true);
    }
}

这是GUI类:

public class JavaApplication19 extends JFrame{
    private final JButton button;
    private final JTextField text;
    private final JLabel lable;



    /**
     * @param args the command line arguments
     */ 
    public JavaApplication19(String title){
        setSize(500, 200);
        setTitle(title);
        setDefaultCloseOperation(JavaApplication19.EXIT_ON_CLOSE);

        button = new JButton("enter only number or i will kill you");
        text = new JTextField();
        lable = new JLabel("numbers only");
        JPanel rbPanel = new JPanel(new GridLayout(2,2));
        rbPanel.add(button);
        rbPanel.add(text);
        rbPanel.add(lable);

        Container pane = getContentPane();
        pane.add(rbPanel);

        button.addActionListener(new ButtonWatcher());

        private class ButtonWatcher implements ActionListener{

        public void actionPerformed(ActionEvent a){
            Object buttonPressed=a.getSource();
            if(buttonPressed.equals(button))
            { 

            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

if(buttonPressed.equals(button))
{
    try {
        //  try something
    }
    catch (NumberFormatException ex) {
        // do something
    }
}

// try something应该是您获取输入文本和解析的代码(ex Integer.parseInt(textField.getText()))。如果解析不起作用,因为没有输入数字,它将抛出NumberFormatException

如果您需要有关如何使用例外的更多信息,请参阅Exceptions tutorial

编辑:方法

像这样的简单工作

public int parseInput(String input) throws NumberFormatException {
    return Integer.parseInt(input); 
}

如果你想捕捉异常

,或类似的东西
public static int parseInput(String input) {
    int number = 0;
    try {
        number = Integer.parseInt(input); 
    } catch (NumberFormatException ex) {
        someLabel.setText("Must be a number");
        return -1;  // return 0 
    }
}

然后在你的actionPerformed中你可以做这样的事情

if(buttonPressed.equals(button))
{
    int n;
    if (parseInput(textField.getText()) != -1){
        n = parseInput(textField.getText());
        // do something with n
    }
}

编辑:布尔方法

public boolean isNumber(String input){
    for (char c : input.toCharArray()){
        if (!Character.isDigit(c))
            return false;
    }
    return true;
}

用法

if(buttonPressed.equals(button))
{
    if (isNumber(textField.getText()){
        // do something
    }
}

修改:或catch例外

public boolean isNumber(String input){
    try {
        Integer.parseInt(input);
        return true;
    } catch (NumberFormatException ex){
        return false;
    }
}