如果希望图形界面有意义,则必须加入事件处理器:
在Swing编程中,依然使用了最早的AWT的事件处理方式所有
的事件处理方式类都是EventObject的子类:
在EventObject类下有AWTEvent子类而又在他的下面有:
IputEvent、ActionEvent、ContainerEvent、TextEvent、WindowEvent等等;
public class EventObject extends Object implements Serializable{
public EventObject(Object source){}
public Object getSource(){//返回一个事件对象
}
public String toString(){}
}
getSource()方法为了就是返回到底是哪个组建被触发;
在之前的事件操作中可以发现,窗体的关闭时无效的,那吗如果
要想让其变得有意义,则必须加入事件处理;
如果要想使用窗体的事件,则必须使用WindowListener完成;
import java.awt.event.WindowListener ;
import java.awt.event.WindowEvent ;
import java.awt.Color ;
import javax.swing.JFrame ;
class MyWindowEventHandle implements WindowListener{
public void windowActivated(WindowEvent e){
System.out.println("windowActivated --> 窗口被选中") ;
}
public void windowClosed(WindowEvent e){
System.out.println("windowClosed --> 窗口被关闭") ;
}
public void windowClosing(WindowEvent e){
System.out.println("windowClosing --> 窗口关闭") ;
System.exit(1) ;
}
public void windowDeactivated(WindowEvent e){
System.out.println("windowDeactivated --> 取消窗口选中") ;
}
public void windowDeiconified(WindowEvent e){
System.out.println("windowDeiconified --> 窗口从最小化恢复") ;
}
public void windowIconified(WindowEvent e){
System.out.println("windowIconified --> 窗口最小化") ;
}
public void windowOpened(WindowEvent e){
System.out.println("windowOpened --> 窗口被打开") ;
}
};
public class MyEventWindowEventJFrame01{
public static void main(String args[]){
JFrame frame = new JFrame("Welcome To MLDN") ;
frame.addWindowListener(new MyWindowEventHandle()) ; // 加入事件
frame.setSize(300,150) ;
frame.setBackground(Color.WHITE) ;
frame.setLocation(300,200) ;
frame.setVisible(true) ;
}
};
思考:
发现在以上的程序中最重要的功能实际上也就是一个关闭,
那么有必要实现这么多方法吗?
所以在事件中提供了很多适配器:
import java.awt.event.WindowAdapter ;
import java.awt.event.WindowEvent ;
import java.awt.Color ;
import javax.swing.JFrame ;
class MyWindowEventHandle extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.out.println("windowClosing --> 窗口关闭") ;
System.exit(1) ;
}
};
public class MyEventWindowEventJFrame02{
public static void main(String args[]){
JFrame frame = new JFrame("Welcome To MLDN") ;
frame.addWindowListener(new MyWindowEventHandle()) ; // 加入事件
frame.setSize(300,150) ;
frame.setBackground(Color.WHITE) ;
frame.setLocation(300,200) ;
frame.setVisible(true) ;
}
};
现在要求只需要一个关闭,那么将他设这成一个累
有些浪费,那么为了解决这样的问题,使用匿名累的
做法;
import java.awt.event.WindowAdapter ;
import java.awt.event.WindowEvent ;
import java.awt.Color ;
import javax.swing.JFrame ;
public class MyEventWindowEventJFrame03{
public static void main(String args[]){
JFrame frame = new JFrame("Welcome To MLDN") ;
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.out.println("windowClosing --> 窗口关闭") ;
System.exit(1) ;
}
}) ; // 加入事件
frame.setSize(300,150) ;
frame.setBackground(Color.WHITE) ;
frame.setLocation(300,200) ;
frame.setVisible(true) ;
}
};
以上是完成了窗口的监听,对按钮也可以;