2015年2月13日 星期五

GUI事件處理 ─ CalculatorEvent

CalculatorEvent
(範例)    修改Calculator,使被點選的按鈕顯示在TextField


import java.awt.*;                                                                       
import java.awt.event.*;

public class CalculatorEvent extends Frame implements ActionListener{
private static final long serialVersionUID = 1L;

TextField tf =new TextField();
String[] txt ={"7","8","9","+","4","5","6","-","1","2","3","*","0",".","=","/"}; 
Button[] btn = new Button[txt.length];

public CalculatorEvent(){
super("Calculator");
add(tf, BorderLayout.NORTH);


Panel p= new Panel();
p.setLayout(new GridLayout(4,4,4,4));
for (int i=0; i<txt.length;i++){
btn [i] = new Button(txt[i]);
btn [i].addActionListener(this);
p.add(btn [i]);
}      
add(p);

setSize(200, 230);
setVisible(true);

}

public static void main(String[] args) {
new CalculatorEvent();

}

@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
tf.setText(cmd);

}

}


沒有留言:

張貼留言