java - XMotion dealing with JComponents -
this question has answer here:
- how move image (animation)? 2 answers
i having trouble. want draw rect onto jpanel added jframe contentpane. want x @ set pos moving -x , restarting +x begins. i.e. if have jpanel 800 x 400, want rext take in parameters moving along xaxis (x - velx) repainting @ 800 , continuing in - x direction. know isn't sufficient info, none of books have touch base on trying lack proper terminology.
// here example of doing this
public class animatedboat {
public static void main(string[] args) { new animatedboat(); } public animatedboat() { eventqueue.invokelater(new runnable() { @override public void run() { try { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) { } jframe frame = new jframe("test"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setlayout(new borderlayout()); frame.add(new animationpane()); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } }); } public class animationpane extends jpanel { private bufferedimage boat; private int xpos = 0; private int direction = 1; public animationpane() { try { boat = imageio.read(new file("boat.png")); timer timer = new timer(40, new actionlistener() { @override public void actionperformed(actionevent e) { xpos += direction; // change directions off window width if (xpos + boat.getwidth() > getwidth()) { xpos = getwidth() - boat.getwidth(); direction *= -1; } else if (xpos < 0) { xpos = 0; direction *= -1; } repaint(); } }); timer.setrepeats(true); timer.setcoalesce(true); timer.start(); } catch (ioexception ex) { ex.printstacktrace(); } } @override public dimension getpreferredsize() { return boat == null ? super.getpreferredsize() : new dimension(boat.getwidth() * 4, boat.getheight()); } @override protected void paintcomponent(graphics g) { super.paintcomponent(g); int y = getheight() - boat.getheight(); g.drawimage(boat, xpos, y, this); } }
}
Comments
Post a Comment