如何从其他文本字段中获取文本字段中的int值

时间:2012-12-17 06:55:50

标签: java swing

我是java的新手。我创建项目,我有一个textField和一个按钮。我为按钮创建功能,我开始其他功能,没关系。但我需要从textField获取数值作为我的函数的参数......

b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                 int price;
                 int quantity = Integer.parseInt(tf2.getText());
                 int totalamount = price*quantity;
              //need to insert this total amout into textfield tf4 //


             tf4.getText(totalamount); //showing error ;   

            }

        });

请帮助我,提前谢谢

4 个答案:

答案 0 :(得分:1)

这很简单......
您可以从文本字段中获取整数值,如

  

int totalamount = Integer.parseInt(tf2.getText());

getText()方法用于从textfield获取值,如果此值为整数,则可以像Integer.parseInt一样对其进行解析。如果此值为string,则可以使用toString()方法获取此值。

您可以将此值设置为

   tf4.setText(String.valueOf(totalamount));  

setText()方法用于将文本设置为Textfield。

您可以在函数调用中使用此值作为调用函数的参数,如

myFunction(totalAmount);// function declaration

在函数定义中使用此值,如

 public void myFunction(int totalamount)// Function Defination

您必须阅读Basic Java。 Here is link which help you

答案 1 :(得分:0)

 b1.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e) { 
       int price; 
       int quantity = Integer.parseInt(tf2.getText()); 
       //int totalamount = price*quantity; 
       //need to insert this total amout into textfield tf4 //

       tf4.setText(totalamount); //showing error ;   

    }

 });

答案 2 :(得分:0)

只需更换此行

tf4.getText(totalamount); 


由这一个

tf4.setText(Integer.toString(totalamount));


OR
tf4.setText(totalamount);
因为TextField已经为Stringsint设置了文字内容。


请记住,你永远不会从getter方法传递一个值(按Java的惯例)。只有setter方法可以传递参数(如果我们在Beans意义上或任何其他方法中考虑它们)请。请遵循Java herehere

的一些基础知识

答案 3 :(得分:0)

b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ 
    //put the try catch here so if user didnt put an integer we can do something else
    try
    {
        int price;
        int quantity = Integer.parseInt(tf2.getText());
        int totalamount = price*quantity;

        //need to insert this total amout into textfield tf4 //

        tf4.setText(totalamount);
    }
    catch(NumberFormatException ex)
    {
          //do something like telling the user the input is not a number
    }   

}});
相关问题