java事件處理5(窗口,窗口坐監視器


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);
            
        }
        
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM