点击一下画一个点

时间:2012-12-04 17:05:15

标签: java swing graphics paintcomponent

您好我想知道如何在MouseClicked方法之外获取鼠标的位置 我需要在有人点击的地方画一个点..这是我现在使用的代码。有人可以帮我这个吗?

    Dot punt = new Dot();

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    punt.setDot(g, getX(), getY(), 5);

    repaint();
}

@Override
public void mouseClicked(MouseEvent m) {
    // TODO Auto-generated method stub
    gebeurtenisverslag.setText( 
            m.getClickCount() + " keer geklikt op " + m.getX() + "," + m.getY());
}

1 个答案:

答案 0 :(得分:5)

为mouseClicked修改的类设置变量。

private int X;
private int Y;

@Override
public void mouseClicked(MouseEvent m) {
    gebeurtenisverslag.setText( 
            m.getClickCount() + " keer geklikt op " + m.getX() + "," + m.getY());
    X = m.getX();
    Y = m.getY();
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    //Probably want to add logic here to verify X & Y have been set
    punt.setDot(g, X, Y, 5);
    repaint();
}