java事件处理5(窗口,窗口坐监视器

时间:2022-07-21 04:59:39

WindowEvent窗口事件

添加接口

addWindowListener(WindowEvent e)

接口有七个方法

public void windowActivated(WindowEvent e)//非激活到激活
public void windowDeactivated(WindowEvent e)//激活到非激活
public void windowClosing(WindowEvent e)//正在被关闭
public void windowClosed(WindowEvent e)//关闭后
public void windowIconified(WindowEvent e)//图标化
public void windowDeiconified(WindowEvent e)//撤销图标化
public void WindowOpened(WindowEvent e)//窗口打开

老实讲上面的方法我也不太清楚什么时候调用,写起来又麻烦

java陪了一个WindowAdapter适配器给我们

WindowAdapter类实现了WindowListener接口的全部方法,我们自己需求的方法只要重写就好

所以我们只需继承WindowAdapter不需要自己实现啦WindowListener啦

class WinPolice extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.out.println("11");
}
}

窗口坐监视器

不用把组件作为参数组合进去,不过程序大的时候容易乱

写窗口的时候实现需要的监视器

class MyWin extends JFrame implements ActionListener{

然后就可以直接在类里面写方法

public void actionPerformed(ActionEvent e)

写个猜数字的测试代码

class MyWin extends JFrame implements ActionListener{
int number;
JTextField text1;
JButton button1,button2;
JLabel label1;
MyWin(){
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
setLayout(new FlowLayout());
button1=new JButton("get a ranbow number");
button2=new JButton("go");
label1=new JLabel("ready");
text1=new JTextField(8);
add(button1);
add(label1);
add(text1);
add(button2);
button1.addActionListener(this);
button2.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() ==button1){
number=(int) (Math.random()*10)+1;
System.out.println(number);
label1.setText("guess");
}
if(e.getSource()==button2){
int t=Integer.parseInt(text1.getText());
System.out.println(t);
if(t<number){
label1.setText("bigger");
text1.setText(null);
}else if(t>number){
label1.setText("smaller");
text1.setText(null);
}else
label1.setText("bigo is "+number); } } }