GUI
Frame
Frame f = new Frame("my frame");
f.setSize(300,200);
f.setLoction(300,150);
f.setVisible(true);
Button bu = new Button("按钮");
f.add(bu);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.out.println("closing");
}
});
- //WindowAdapter(适配器)是一个匿名内部类,覆盖了addWindowLister抽象类的7个方法,而我们只需要覆盖WindowAdapter中我们需要的方法即可
- 适配器的存在是为了更好的创建监听器对象,当监听器中的方法超过两个时,该监听器一般都有适配器
事件监听机制
ActionListener(活动监听器)
为按钮添加一个活动监听器,目的:一点击按钮程序关闭
bu.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
鼠标和键盘事件
public class MouseAndKeyDemo{
private Frame f;
private TextField tf;
private Button b
public MouseAndKeyDemo(){
init();
}
private void init(){
f = new Frame("演示键鼠监听器");
f.setBounds(400,200,300,200);
f.setLayout(new FlowLayout());
tf = new TextField(15);
b = new Button("anniu");
f.add(b);
f.add(tf);
myevent();
f.setVisible(true);
}
private void myevent(){
tf.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
System.out.println("key run"+KeyEvent.getKeyText(e.getKeyCode()));
}
});
f.addActionListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
b.addMouseListener(new MouseAdapter(){
private int count =1;
public void mouseEntered(MouseEvent e){
tf.setText("mouse enter:"+count++);
}
public void mouseClick(MouseEvent e){
if(e.getClickCount()==2)
tf.setText("mouse click:"+count++);
}
});
}
}