一、事件监听
public class TestListener {
public static void main(String[] args) {
Frame frame = new Frame();
Button button = new Button("buttom");
ActionListener actionListener = new MyActionListener();
button.addActionListener(actionListener);
frame.add(button);
frame.setSize(500,500);
frame.setVisible(true);
WindowC(frame);
}
//把关闭窗口抽象成一个方法
public static void WindowC(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("触发了button");
}
}
两个按钮、共享同一个事件
二、TextField事件监听
(frame.pack():会自适应)
public class TestTextField {
public static void main(String[] args) {
testFramex testFrame1 = new testFramex();
}
}
class testFramex extends Frame{
public testFramex(){
TextField textField = new TextField();
add(textField);
textFiledActionListener textFiledActionListener = new textFiledActionListener();
textField.addActionListener(textFiledActionListener);
textField.setEchoChar('*');//隐藏输入
setSize(500,500);
setVisible(true);
}
}
class textFiledActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField) e.getSource();
System.out.println(field.getText());
field.setText("");
}
}
三、回顾(组合+内部类)
class A extentd B{
}
class A{
public B b; //组合B的全部方法属性
}
多态和继承都会导致代码变负载,尽量用组合的方式。