1. 程式人生 > >Java的GUI學習七(滑鼠事件)

Java的GUI學習七(滑鼠事件)

  學習來自:

http://www.cnblogs.com/xingyunblog/p/3850400.html

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class frame {
    private Frame f;
    private Button but;
    frame(){init();}
	public void init() {
		f = new Frame("視窗");
		f.setBounds(300,100,600,500);
		f.setLayout(new FlowLayout());
		but = new Button("我是按鈕");
		f.add(but);
		dealwithEvent();
		f.setVisible(true);
	}
	//事件監聽器以及處理事件
	private void dealwithEvent()
	{
		//窗體關閉監聽
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		//按鈕活動監聽器以及處理事件
		but.addActionListener(new ActionListener() {
			private int actioncount = 1;
			public void actionPerformed(ActionEvent e) {
				System.out.println("按鈕被活動"+ actioncount+++"次");
			}
			
		});
		//滑鼠進入按鈕聽觸發事件以及滑鼠被雙擊監聽觸發事件
		but.addMouseListener(new MouseAdapter() {
			private int count = 1;
			private int clickCount = 1;
			public void mouseEntered(MouseEvent e) {
				System.out.println("滑鼠進入到該元件"+count+++"次");
			}//這邊是滑鼠移動到這裡 所以就會出現這個
			 public void mouseClicked(MouseEvent e)
             {
                 if(e.getClickCount()==2) 
                 System.out.println("雙擊被執行"+clickCount+++"次");
             }
		});
	}
    //按鈕活動監聽器以及處理時間
    public static void main(String[] args) {
    	new frame();
    }

}