I've created a class Circle which extends JPanel, and uses the paint method. I've also implemented a move method . The move method uses a while loop to change the existing x and y coordinate points to the new x and y coordinate points by one point each time. I've tested the Circle class, and it works correctly. However, I wanted to direct the coordinates to a point at which the user clicks, I implemented a MouseListener. I was able to use the method c.move(e.getX(), e.getY()) just fine, the circle does move, but it does not repaint itself, instead it just repaints itself after it has finished moving, so it just appears at its destination instead of moving there gradually.
Main class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
/**
*
* @author programming
*/
public class Main {
public static Circle c = new Circle();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.add(c);
frame.setVisible(true);
c.move(200, 200);
c.move(250, 100);
c.move(300, 300);
c.move(600, 200);
c.move(400, 100);
c.move(100, 50);
c.move(0, 0);
frame.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
c.move(e.getX(), e.getY());
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
}
Circle class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
/**
*
* @author programming
*/
public class Circle extends JPanel {
private int x = 0, y = 0;
private boolean init = true;
public Circle() {
}
public void paint(Graphics g) {
super.paintComponent(g);
super.setOpaque(false);
g.drawOval(x, y, 10, 10);
}
public void move(int x, int y) {
while(this.x != x || this.y != y) {
if (this.x < x) {
this.x++;
} else if (this.x > x) {
this.x--;
}
if (this.y < y) {
this.y++;
} else if (this.y > y) {
this.y--;
}
this.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
}
}
System.out.println("X: " + this.x + " " + x + " Y: " + this.y + " " + y);
}
}
Basically I'd just like to know if anyone has faced this problem before and could assist me with it.
Thanks,
satar
Edit:
Just realized this should be in awt, sorry.