import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class AppWindow extends Frame {
String keyMessage = "";
String MouseMsg = "";
int mouseX = 10;
int mouseY = 40;
int locX = 0;
int locY = 0;
public AppWindow() {
addMouseListener(new MyMouseAdaptor(this));
}
public void paint(Graphics g) {
g.drawString(keyMessage, mouseX, mouseY);
g.drawString(MouseMsg, locX, locY);
}
public static void main(String[] args) {
AppWindow appWindow = new AppWindow();
appWindow.setSize(400, 400);
appWindow.setVisible(true);
}
}
class MyMouseAdaptor extends MouseAdapter implements MouseListener {
AppWindow appWindow;
public MyMouseAdaptor(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent e) {
this.appWindow.MouseMsg = "Mouse Pressed at : " + e.getX() + ", "
+ e.getY();
this.appWindow.locX = e.getX();
this.appWindow.locY = e.getY();
this.appWindow.repaint();
}
}
親愛的所有java如何知道mousePressed()事件何時發生?
我有一個奇怪的問題。我知道上述代碼中的所有內容,但我錯過了一些東西。 Java如何知道mousePressed事件何時發生?我需要爲自己的邏輯找到答案。在哪裏寫的代碼,說
when the user press the mouse -- > trigger the method "public void mousePressed(MouseEvent e)" and do what is inside it
感謝
親愛的。謝謝你的答案..我知道你提到的所有..我的問題是..如何知道java何時按下的方法,因爲有一個代碼,內置在Java中說(當用戶按下鼠標 - >觸發方法「public void mousePressed(MouseEvent e)」並做它裏面的東西)..請考慮一下.. – 2014-09-28 05:07:48
正如我在回答中寫的,MouseAdaptor是一個抽象類,用於創建偵聽器對象它偵聽任何鼠標事件,並且一旦該事件發生,就會調用相應的方法,並將鼠標事件傳遞給它。接口MouseListener也一樣。 – 2014-09-28 05:15:26
我認爲EventListener是編寫代碼的地方,它允許Java監聽事件並調用相應的方法,因爲所有事件監聽器都會擴展EventListener。 – 2014-09-28 05:19:35