2012-12-17 110 views
1

我是新来的java。我创建项目,我有一个textField和一个按钮。我做按钮的功能,在那里我开始我的其他功能,没关系。但是,我需要从文本框取数的值作为参数为我的功能...如何从其他文本字段的文本字段中获取int值

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 ; 

      } 

     }); 

帮我请,谢谢你提前

+0

您是否想要设置总金额为tf4?只是做tf4.setText(Integer.toString(totalamount)); – Freak

+0

tf4.getText(Integer.toString(totalamount)); – StanislavL

+0

你想做什么... – Parth

回答

1

这很简单...
你可以从文本字段获得整数值,如

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

的getText()方法是使用从文本框获取值,如果这个值是整数,你可以解析它喜欢的Integer.parseInt,如果这个值是字符串,那么你可以得到这样的使用值的toString()方法。

,你可以设置像

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

setText()方法这个值是使用将文本设置为文本字段。

您可以使用函数调用这个值作为参数来调用函数像

myFunction(totalAmount);// function declaration 

而且在功能定义使用此值喜欢

public void myFunction(int totalamount)// Function Defination 

您必须阅读基本的Java。 Here is link which help you

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 ; 

    } 

}); 
+0

出现错误是因为你实际上从tf4获取文本。相反,您必须将文本设置为totalamount。 –

0

只凭这一个

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


OR
tf4.setText(totalamount);
更换您此行

tf4.getText(totalamount); 


因为TextField已经overloded为Stringsint设置文本的方法。


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

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 
    } 

}}); 
相关问题