Circle to move when mouse clicked Java

Posted by Myt on Stack Overflow See other posts from Stack Overflow or by Myt
Published on 2012-09-23T09:24:39Z Indexed on 2012/09/23 9:37 UTC
Read the original article Hit count: 233

Filed under:

So I am really new to Java and I need a circle to move around JFrame when it's clicked, but the circle has to get random cordinates. So far this code generates a new circle every time it's clicked, but all the other circles stay there aswell, but I only need one circle to move around the frame. So maybe someone can help me a little :)

public class test2 extends JFrame implements MouseListener {
int height, width;
public test2() {
    this.setTitle("Click");
    this.setSize(400,400);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    addMouseListener(this);
    width = getSize().width;
    height = getSize().height;
}

public void paint (Graphics g) {
    setBackground (Color.red);
    g.setColor(Color.yellow);
    int a, b;
    a = -50 + (int)(Math.random()*(width+40));
    b = (int)(Math.random()*(height+20));
    g.fillOval(a, b, 130, 110);
}

    public void mouseClicked(MouseEvent e) {
    int a, b;
    a = -50 + (int)(Math.random()*(width+40));
    b = (int)(Math.random()*(height+20));
    repaint();
}

public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}

public static void main(String arg[]){

    new test2();
}

}

© Stack Overflow or respective owner

Related posts about java