修飾子與參數
public int getY()
getY() 的回傳值 (return value) 為 int 型態 (type) 的整數常數,非物件 (object) ,不需要參數 (paramenter) 。
舉例如下
import java.awt.*; import java.awt.event.*; public class MouseEventDemo extends MouseAdapter { Frame frame; Panel panel; Label text; public static void main(String[] args) { new MouseEventDemo(); } public MouseEventDemo() { frame = new Frame("AWTDemo"); frame.addWindowListener(new AdapterDemo()); frame.setSize(600, 400); panel = new Panel(); panel.addMouseListener(this); text = new Label("something happened.."); panel.add(text); frame.add(panel, BorderLayout.CENTER); frame.setVisible(true); } public void mousePressed(MouseEvent e) { text.setText("x: " + e.getX() + ", y: " + e.getY()); System.out.print("screen x: " + e.getXOnScreen()); System.out.print(", y: " + e.getYOnScreen() + "\n"); if (e.getButton() == MouseEvent.BUTTON1) { System.out.println("left button"); } if (e.getButton() == MouseEvent.BUTTON2) { System.out.println("middle button"); } if (e.getButton() == MouseEvent.BUTTON3) { System.out.println("right button"); } System.out.println("mouse position: " + e.getPoint()); System.out.println("mouse screen position: " + e.getLocationOnScreen()); System.out.println("mouse clicks: " + e.getClickCount()); } } class AdapterDemo extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } /* 《程式語言教學誌》的範例程式 http://pydoing.blogspot.com/ 檔名:MouseEventDemo.java 功能:示範 Java 程式 作者:張凱慶 時間:西元 2012 年 3 月 */
此例的 MouseEventDemo 直接繼承 MouseAdapter 類別
public class MouseEventDemo extends MouseAdapter {
由於 MouseAdapter 已經實作 MouseListener 介面,因此這裡我們直接改寫 mousePressed() 方法,當滑鼠按鍵被按下就會執行 mousePressed() 。首先呼叫 MouseEvent 的 getX() 與 getY() 取得在視窗中點擊的座標,並且顯示在視窗的 Label 中,然後在命令列呼叫 getXOnScreen() 與 getYOnScreen() 印出在螢幕中點擊的座標,接著呼叫 getButton() 判斷按下哪一個鍵,最後呼叫並印出 getPoint() 、 getLocationOnScreen() 與 e.getClickCount()
public void mousePressed(MouseEvent e) { text.setText("x: " + e.getX() + ", y: " + e.getY()); System.out.print("screen x: " + e.getXOnScreen()); System.out.print(", y: " + e.getYOnScreen() + "\n"); if (e.getButton() == MouseEvent.BUTTON1) { System.out.println("left button"); } if (e.getButton() == MouseEvent.BUTTON2) { System.out.println("middle button"); } if (e.getButton() == MouseEvent.BUTTON3) { System.out.println("right button"); } System.out.println("mouse position: " + e.getPoint()); System.out.println("mouse screen position: " + e.getLocationOnScreen()); System.out.println("mouse clicks: " + e.getClickCount()); }
編譯後執行,結果如下
中英文術語對照 | |
---|---|
類別 | class |
方法 | method |
屬性 | field |
回傳值 | return value |
您可以繼續參考
事件處理
相關目錄
Java API 分類導覽
Java 教材
首頁
參考資料
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseEvent.html
沒有留言:
張貼留言