我从学习资源中获取了以下代码。当我运行applet时,我注意到'Up'仅在拖动鼠标后显示。如果按下鼠标按钮然后在同一位置释放,则不会显示“向上”。为什么在后一种情况下不显示'Up'?
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent mld) {
mouseX = 0;
mouseY = 20;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent mld) {
mouseX = 0;
mouseY = 30;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent mld) {
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent mld) {
// save coordinates
mouseX = mld.getX();
mouseY = mld.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent mld) {
// save coordinates
mouseX = mld.getX();
mouseY = mld.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent mld) {
// save coordinates
mouseX = mld.getX();
mouseY = mld.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent mld) {
// show status
showStatus("Moving mouse at " + mld.getX() + ", " + mld.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
答案 0 :(得分:0)
拖动时mouseClicked
将不会被调用,但mouseReleased
将被调用。在单个位置点击后,mouseReleased
后跟mouseClicked
,因此被点击的活动会覆盖已发布的内容
尝试将System.out.println
语句添加到MouseListener
方法中并跟踪控制台中的输出...
// Handle mouse clicked.
public void mouseClicked(MouseEvent mld) {
mouseX = 0;
mouseY = 20;
msg = "Mouse clicked.";
System.out.println("clicked");
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent mld) {
// save coordinates
mouseX = mld.getX();
mouseY = mld.getY();
msg = "Down";
System.out.println("down");
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent mld) {
// save coordinates
mouseX = mld.getX();
mouseY = mld.getY();
msg = "Up";
System.out.println("up");
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent mld) {
// save coordinates
mouseX = mld.getX();
mouseY = mld.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
System.out.println("dragged");
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent mld) {
// save coordinates
mouseX = mld.getX();
mouseY = mld.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
System.out.println("dragged");
repaint();
}
你应该看到......
down
up
clicked
单击一个点,但
down
dragged
.
.
.
up
被拖动