我正在尝试计算 mouseClicks,但我不明白为什么我的计数器每次单击都会增加 2。尝试了 getClickCount(),但这也不是我需要的。
计数后我的目标:我会使用计数器以不同的点击次数绘制不同的东西。假设第 1 次和第 2 次将始终获得 drawLine() 的坐标,而第 3 次单击将获得 drawRect()。
package graphics_training_painting;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class U4 extends Canvas implements MouseListener{
private int x1;
private int y1;
private int x2;
private int y2;
private int counter = 0;
public U4() {
setBackground(Color.white);
}
public static void main(String[] args) {
U4 u = new U4();
JFrame f = new JFrame();
f.add(u);
f.setSize(800, 600);
f.setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e) {
counter++;
System.out.println(counter);
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
/* x1 = e.getX();
y1 = e.getY();*/
}
@Override
public void mouseReleased(MouseEvent e) {
/* x2 = e.getX();
y2 = e.getY();
repaint();*/
}
public void paint(Graphics g) {
addMouseListener(this);
g.setColor(Color.blue);
g.drawLine(x1, y1, x2, y2);
}
}
非常感谢您的帮助或建议,蒂米!