java - how do I update new image on JFrame ? (I tried everything but it didn't work) -
so source code, i'm trying make stick man moving first, tried make head moving. works, problem past movement , reccentt movement stick goes ooooooooooo when it's supposed go o
i tried repaint() validate() updateui() still didn't work
any idea?
package jamestestpackage; import java.awt.*; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.awt.event.keyevent; import java.awt.event.keylistener; import javax.swing.*; public class stickmanui extends jpanel implements actionlistener, keylistener{ timer t = new timer(1,this); int x=180; int x_vel = 0; int y_vel = 0; public stickmanui(){ t.start(); addkeylistener(this); setfocusable(true); } public void paintcomponent(graphics g) { graphics2d g2 = (graphics2d) g; g2.setstroke(new basicstroke(5)); g2.drawline(200, 50, 200, 100); // body g2.drawline(200, 100, 220, 150); // right leg g2.drawline(200, 100, 180, 150); // left leg g2.drawline(200, 75, 170, 100); //left arm g2.drawline(200, 75, 230, 100); //right arm g2.drawoval(x, 10, 40, 40); // head } @override public void actionperformed(actionevent arg0) { // todo auto-generated method stub x= x + x_vel; repaint(); } @override public void keypressed(keyevent arg0) { // todo auto-generated method stub if(arg0.getkeycode()==keyevent.vk_right) x_vel = 1; else if(arg0.getkeycode() == keyevent.vk_left) x_vel = -1; } @override public void keyreleased(keyevent arg0) { // todo auto-generated method stub x_vel =0; } @override public void keytyped(keyevent arg0) { // todo auto-generated method stub } }
when doing custom painting first statement in paintcomponent() method should be:
super.paintcomponent(g);
to make sure background cleared before painting done.
read section swing tutorial on custom painting more information , working examples started.