I am using below code to move a rectangle on a Canvas -
First time when i run my program, rectange comes fine but when i click on the move button it doesn't.
Below is my code to do that -
public void actionPerformed(ActionEvent ae)
{
for (int i=0;i<10 ;i++ )
{
(MyPictureAct.x)++;
mt.repaint(); ///mt is object reference of my Canvas object
System.out.println(MyPictureAct.x);
public void paint(Graphics g)
{
g.draw3DRect(MyPictureAct.x,70,20,20,true);
}
}
Could you please tell me what is the wrong in this or is there any another good way of doing that.
Its printing the increasing value of x in for loop so loop is fine.
As i see in API,
The default operation is simply to clear the canvas. Applications that override this method need not call super.paint(g).
but even after using it no luck.
seems it not entering in the paint method when i call repaint.
Are you sure that you want to mix Swing components (JApplet) with AWT components (Canvas)? I think that doing this without need and knowledge is a recipe for disaster. Instead I recommend that you use a JPanel to draw on, that you override its paintComponent method, and that you call super.paintComponent(g) as the first call in this override.
Best of luck.
edit: you're also calling thread.sleep on the EDT, or Event Dispatch Thread, which will make your program almost completely non-responsive. The EDT is the single Swing thread responsible for user interaction (button presses and keyboard input, etc...) and for drawing components. When you put it to sleep, the app can't interact with the user or draw itself.
Instead of Thread.sleep, please look into using a Swing Timer here.
Hi Pete,
Even if i use Applet instead of JApplet samething happens. don't know as to why its not entering in paint method.
also with JPanel if i want to call paintComponent again as i did using repaint in canvas then we do have similiar method here too.
rePaint(x,y,wid,ht)... but again same results as i got with canvas.. it not entering inside paintComponent from for loop.
so Manoj, is everything working as it should in your case?
i also just opened my own thread about issues with painting custom JComponents, but the problem is a little different i guess since i dont use any layout manager...
anyway, might still be helpful to somebody or even someone can give me a hint...