2014-01-25 138 views
-1

我有以下代碼。當按下按鈕時,我將如何使文本框顯示每個按鈕上的文本?我在網上開始java課程,幾乎沒有任何指示,然後讓我做這樣的事情,所以任何和所有的幫助,非常感激。我想學習!謝謝!如何用按鈕觸發文本框

import java.awt.*; 
public class FinalProj2 extends Frame 
{ 
FinalProj2() 
{ 
    setTitle("Buttons"); 
    setSize(600,600); 
    show(); 
} 
public static void main(String args[]) 
{ 
    Frame objFrame; 
    Button objButton1; 
    Button objButton2; 
    Button objButton3; 
    Label objLabel2; 

    objFrame= new FinalProj2(); 
    objButton1= new Button("Submit"); 
    objButton2= new Button("Cancel"); 
    objButton3= new Button("What Now"); 
    objLabel2= new Label(); 


    objButton1.setBounds(60,200,80,80); 
    objButton2.setBounds(150,300,80,80); 
    objButton3.setBounds(60,400,80,80); 


    objFrame.add(objButton2); 
    objFrame.add(objButton1); 
    objFrame.add(objButton3); 
    objFrame.add(objLabel2); 
} 
} 

回答

1

使用安裝在每個你所需要的按鈕實例addActionListener()方法一個ActionListener。在文本框中

btn.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     lbl.setText(btn.getLabel()); 
    } 
}); 
0

如果我理解正確actionPerformed()法文本,你想,當你按下任何按鈕,然後單擊按鈕標籤應顯示在TextField

對於這一點,你必須創建文本字段的對象像:

objButton1.addActionListener(new ActionListener() { 
public void actionPerformed(ActionEvent e) { 
    box.setText(objButton1.getLabel()); 
} 
}); 

final TextField box = new TextField(); 

然後你就可以在該文本字段添加喜歡的ActionListener

其他按鈕也一樣。