Hi i was trying to make a 2D game. For this i am required to move a rectangle placed on a JFrame in the x-axis when the mouse is moved. My mouseMoved method call a user-defined moveTo method in another class, passing the x-coordinate as argument.
This moveTo function is responsible for changing the current location of the rectangle and invoking repaint().
But the problem is that the repaint method is just ignored i.e. nothing happens when it is called.
Bellow is the code of the class which is responsible for creating the rectangle object, defining paintComponent and moveTo methods, and calling repaint.
CODE
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class MyBase extends JComponent
{
private int xCord=0;
private static final int YCORD=0;
private static final int WIDTH=20;
private static final int HEIGHT=30;
private Rectangle box;
public MyBase()
{
box = new Rectangle(xCord,YCORD,WIDTH,HEIGHT);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(box);
System.out.println("paint");
}
public void moveTo(int x)
{
box.setLocation(x,YCORD);
repaint();
System.out.println(box);
}
}
I am very new to java programming, so please help me out with this. This problem has been bugging me for quite a long. By the way i am using OpenSuSe 10.2 OS and JDK 1.6