Java---鼠標事件小實例

    關於鼠標事件知識點很簡單,也就那幾個方法,但在實際開發中應用是十分靈活的,結合知識點試着做了一個小案例。

   實現的效果圖:

                            

代碼清單:

       package Swing;


import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;


import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
public class MouseEvent2 extends JFrame {

 
public MouseEvent2() {
this.setTitle("鼠標事件");   //設置窗體標題
this.setBounds(100, 100, 473, 321);//設置窗體顯示座標及窗體大小
this.setVisible(true); //設置窗體可見
this.setResizable(false); //設置窗體大小不可改變
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //設置窗體默認關閉程序

this.getContentPane().setLayout(null); //添加容器並設置容器佈局

JLabel label=new JLabel("     --------來點我啊---------");    //標籤
label.setBounds(240, 57,160,200);
label.setBorder(new LineBorder(Color.red, 2));
getContentPane().add(label);


JLabel label1=new JLabel("鼠標點擊區域");   //標籤
label1.setBounds(281, 32,84, 15);
getContentPane().add(label1);

JScrollPane scrollpane=new JScrollPane();  //容器
scrollpane.setBounds(32, 27, 183, 216);
getContentPane().add(scrollpane);


JTextArea textatea=new JTextArea();  //創建文本域
scrollpane.setViewportView(textatea);     //添加文本到
   
        
         label.addMouseListener(new MouseListener() {


public void mouseReleased(MouseEvent e) {   //鼠標釋放監聽
    
textatea.append("鼠標釋放啦....\n");
}

public void mousePressed(MouseEvent e) {    //鼠標按下監聽
 
textatea.append("鼠標按下啦....\n");
}


public void mouseExited(MouseEvent e) {   //鼠標離開監聽
textatea.append("鼠標離開啦....\n");

}


public void mouseEntered(MouseEvent e) {   // 鼠標進入監聽
textatea.append("鼠標進入啦....\n");
   double x=textatea.getX();    //鼠標座標
   double y=textatea.getY();
textatea.append("鼠標此時的座標爲:"+x+","+y+"\n");

}


public void mouseClicked(MouseEvent e) {   //鼠標單擊監聽
    
   int btn=e.getButton();   //記錄鼠標哪一個鍵被按下,返回一個int值
switch(btn) {
case  MouseEvent.BUTTON1:
textatea.append("鼠標左鍵點擊了\n");
break;
case  MouseEvent.BUTTON2:
textatea.append("鼠標滑輪點擊了\n");
break;
case  MouseEvent.BUTTON3:
textatea.append("鼠標右鍵點擊了\n");
break;
}

int count=e.getClickCount();  //記錄鼠標單擊的次數。返回一個int值
textatea.append("鼠標單擊了"+count+"次\n");
}
});
        
}
/**
* 程序入口
* @param args
*/
    public static void main(String[] args) {
   new MouseEvent2();
       
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章