您需要使用接口ActionListener並在單擊按鈕 後添加ActionListener。實現默認方法ActionPerformed。以此代碼爲例。
import java.awt.*;
import java.awt.event.*;
class calc extends Frame implements ActionListener
{
TextField t1 =new TextField(20);
TextField t2 =new TextField(29);
TextField t3 =new TextField(29);
Label l1=new Label("first");
Label l2=new Label("second");
Label l3=new Label("sum");
Button b1=new Button("Add");
Button b2=new Button("close");
calc() //CONSTRUCTOR
{
add(l1);add(t1);
add(t2);add(l2);
add(t3);add(l3);
add(b1);
add(b2);
setSize(444,555);
setVisible(true);
setLayout(new FlowLayout());
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object o=e.getSource();
if(o==b2)
{
System.exit(1);
}
String n1=t1.getText();
String n2=t2.getText();
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
t3.setText(""+(a+b));
}
}
class Gi
{
public static void main(String[] args)
{
new calc();
}
}
在NetBeans中,您可以在窗體設計器中將JButton的enabled屬性設置爲false。爲什麼不這樣做? –
我是Netbeans的新手,我不知道如何做到這一點 –
而這只是禁用它無法在其他按鈕被按下後再次啓用 –