从文本字段中获取数据并将其显示在另一个文本字段中

时间:2015-04-27 14:44:26

标签: java swing actionlistener

//combo box actionperformed method.

private void CmbActionPerformed(java.awt.event.ActionEvent evt) {                                    
//created aray of objects

    JTextField t[]=new JTextField[8];

    String num=null,s1;
    int num1=0;
    num=Cmb.getSelectedItem().toString();
    num1=Integer.parseInt(num);
    //applied a logic to create same no. of textfields that selected in combo box.   

    while(num1!=0){ 
        for(int i=0;i<num1;i++)
        {
            t[i]=new JTextField(10);
            jPanel2.add(t[i]);
            b1.setText("the objects has created");
            jPanel2.revalidate();
            validate();
            num1--;
        }
    }
}
//actionperformed method of buuton b1.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 

    String a1;
    a1=t1.getText();

    //getting error t1 not found;
    //I think it is because t1 is local aray of comboactionperformedmethod and cant be accessed by this method. I need ur help to solve this. 

    b1.setText(s1);  
}

1 个答案:

答案 0 :(得分:1)

最简单的方法是将文本区域字段声明为类成员变量,而不是在方法内。然后该类中的其他方法可以访问它们。

JTextField t[]=new JTextField[8];
//created aray of objects

private void CmbActionPerformed(java.awt.event.ActionEvent evt)
{

然后:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 

    String a1;
    a1=t[0].getText();

还要注意访问数组成员的正确方法。