简体   繁体   English

无法从JTextField获取整数

[英]Can't get integer from JTextField

I'm trying to get an integer from a JTextField , but I keep getting a NumberFormatException . 我试图从JTextField获取一个整数,但我一直在获取NumberFormatException I used the code below: 我使用下面的代码:

JTextField price = new JTextField();
price.addActionListener(new ComboListener());
String inputText = price.getText();
int inputPrice = Integer.parseInt(inputText);

Every site says this is the proper way to do it, so I don't understand what I'm doing wrong. 每个站点都说这是正确的方法,所以我不明白自己在做什么错。

edit: The full code is here: 编辑:完整代码在这里:

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

public class RatePanel extends JPanel {

    private double[] rate; // exchange rates
    private String[] currencyName;
    private JLabel result;

    public RatePanel() {
        currencyName = new String[]{"Select the currency..",
            "European Euro", "Canadian Dollar",
            "Japanese Yen", "Australian Dollar",
            "Indian Rupee", "Mexican Peso"};

        rate = new double[]{0.0, 1.2103, 0.7351,
            0.0091, 0.6969, 0.0222, 0.0880};

        JLabel title = new JLabel("How much is that in dollars?");
        title.setAlignmentX(Component.CENTER_ALIGNMENT);
        title.setFont(new Font("Helvetica", Font.BOLD, 20));
        add(title);
        add(Box.createRigidArea(new Dimension(0, 100)));
        JLabel enter = new JLabel("Enter cost of item");
        enter.setAlignmentX(Component.LEFT_ALIGNMENT);
        enter.setFont(new Font("Helvetica", Font.BOLD, 20));
        add(enter);
        JTextField price = new JTextField();
        price.addActionListener(new BoxListener());
        price.setAlignmentX(Component.RIGHT_ALIGNMENT);
        add(price);
        add(Box.createRigidArea(new Dimension(0, 100)));
        JLabel select = new JLabel("Select a currency: ");
        select.setAlignmentX(Component.LEFT_ALIGNMENT);
        select.setFont(new Font("Helvetica", Font.BOLD, 20));
        add(select);
        JComboBox Cbox = new JComboBox(currencyName);
        Cbox.addActionListener(new ComboListener());
        Cbox.setAlignmentX(Component.RIGHT_ALIGNMENT);
        add(Cbox);
        String index = Cbox.getSelectedItem().toString();
    }

    public class BoxListener implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            String inputText = price.getText();
            int inputPrice = Integer.parseInt(inputText);
        }
    }

    public class ComboListener implements ActionListener {

        public void actionPerformed(ActionEvent event, String index, double inputPrice, double[] rate) {
            double finalPrice = 0;
            switch (index) {
                case "European Euro":
                    finalPrice = inputPrice * rate[1];
                    break;
                case "Canadian Dollar":
                    finalPrice = inputPrice * rate[2];
                    break;
                case "Japanese Yen":
                    finalPrice = inputPrice * rate[3];
                    break;
                case "Australian Dollar":
                    finalPrice = inputPrice * rate[4];
                    break;
                case "Indian Rupee":
                    finalPrice = inputPrice * rate[5];
                    break;
                case "Mexican Peso":
                    finalPrice = inputPrice * rate[6];
                    break;
            }

            result = new JLabel(inputPrice + "USD equals " + finalPrice
                    + index);
            add(result);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}

I ran your code, it actually works fine (without giving me NumberFormatException ). 我运行了您的代码,它实际上运行良好(没有给我NumberFormatException )。

You get NumberFormatException probably because you attempted the following: 您收到NumberFormatException原因可能是您尝试了以下操作:

  1. Press Enter on the textfield when the field is empty 当字段为空时,在文本字段上按Enter键
  2. Press Enter on the textfield when the field contains non-numeric input 当字段包含非数字输入时,请在文本字段上按Enter键

You could add validations to your input before attempting to parse the textfield's content into integer: 您可以在尝试将文本字段的内容解析为整数之前,向输入中添加验证:

public class BoxListener implements ActionListener {

    public void actionPerformed(ActionEvent event) {
        String s= price.getText();
        if(s.matches("[0-9]+"))               //Perform validation before parsing string
            inputPrice = Integer.parseInt(s);
    }
}

Also note that, instead of declaring inputPrice and your other components such as your textfields as local variables, I declared them as instance variables of RatePanel . 还要注意,我没有将inputPrice和其他组件(如文本字段)声明为局部变量,而是将它们声明为RatePanel实例变量。


To declare your variables as instance variable instead of local variables: 要将变量声明为实例变量而不是局部变量:

class RatePanel extends JPanel{
    private JTextfield txtPrice;   // <--- declare here as instance variable
    private int inputPrice;        // <--- declare here as instance variable

    public RatePanel(){
        //If you declare in the constructor or other methods, they become local variables.
    }
}

When I try to define it in the actionListener method, it tells me it can't find the textbook 当我尝试在actionListener方法中定义它时,它告诉我找不到教科书

That is probably because you define 'price' as a local variable in the method that you create it. 那可能是因为您在创建价格的方法中将“价格”定义为局部变量。 Your 'price' variable should be an instance variable that is visible to all methods in your class. 您的“价格”变量应该是实例变量,该变量对于您的类中的所有方法均可见。

First of all, the code as written tries to access the text right after the text field is created, before the user has typed anything into it. 首先,编写的代码会在创建文本字段之后,在用户向其中键入任何内容之前立即尝试访问文本。 The code accessing the text should be inside the action listener. 访问文本的代码应在动作侦听器内。 If ComboListener is a class that you created, then the last two lines should be in its actionPerformed method; 如果ComboListener是您创建的类,则最后两行应在其actionPerformed方法中;否则,请ComboListener该类中。 if you do it that way, make sure that the price variable is an instance variable or static variable (ie, outside a method definition—whether to make it static and which class to put it in depends on how the rest of your code is structured). 如果这样做,请确保price变量是实例变量或静态变量(即,在方法定义之外),是否使其成为静态变量以及将其放入哪个类取决于其余代码的结构)。

An alternative way is to use an anonymous inner class, like this: 另一种方法是使用匿名内部类,如下所示:

// the 'final' modifier is necessary for anonymous inner classes
// access local variables
final JTextField price = new JTextField();
price.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String inputText = price.getText();
        // do the conversion and other processing here...
    }
});

(I believe in newer versions of Java this can be abbreviated as (我相信在Java的较新版本中,可以将其缩写为

price.addActionListener((ActionEvent e) -> {
    String inputText = price.getText();
    // do the conversion and other processing here...
});

but I'm not 100% sure about that.) 但我对此不是100%的肯定。)

Second, keep in mind that if you use parseInt , it'll only accept whole number values; 其次,请记住,如果使用parseInt ,它将仅接受整数值; things like 12.34 (with a decimal point) will cause an error. 诸如12.34 (带小数点)之类的内容将导致错误。 The simplest way to fix this is to use Double.parseDouble , although using double s with prices can cause rounding errors, so it's not the best way to do it. 解决此问题的最简单方法是使用Double.parseDouble ,尽管对价格使用double会导致舍入错误,因此这不是最佳方法。 Also, make sure you don't put a $ or £ or or whatever in the box; 另外,请确保不要在框中输入$£或其他字样; that could also cause an error. 这也可能导致错误。

You are reading a JTextField immediately after creating it. 创建JTextField后,您将立即读取它。 At that point, it's empty empty string, which is not a valid number. 此时,它是一个空的空字符串,不是有效数字。

You should put that code in the listener where it will fire when the user presses Enter or something. 您应该将该代码放在用户按Enter或其他命令时将在其中触发的侦听器中。 And, additionaly, try to be nice to the user and show an error message instead of throwing an exception. 另外,请尝试对用户友好,并显示错误消息,而不是引发异常。

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

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