1.创建一个图形界面,需要使用frame窗口
2.窗口中可以添加Component组件,大部分的组件都已经实现了Component接口,所以可以直接添加。
3.可以在实现了Component接口的组件中添加ActionListener监听事件。
4.可以在Frame对象中添加WindowAdapter对象使Frame对象实现退出的功能
例4.
class Exit extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Exit exit = new Exit();
frame.addWindowListener(exit);
package study02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestText {
public static void main(String[] args) {
new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame(){
this.setBounds(500,500,200,200);
TextField textField = new TextField();
this.add(textField);
MyAction myAction = new MyAction();
textField.addActionListener(myAction);
// textField.setEchoChar('*');
this.add(textField);
this.setVisible(true);
Exit exit = new Exit();
this.addWindowListener(exit);
}
}
class MyAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField) e.getSource();
System.out.println(field.getText());
field.setText("");
}
}
class Exit extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}