Monday, 15 August 2011

java - Why doesn't the ball show up in the frame if I add the ball after the for loop? -



java - Why doesn't the ball show up in the frame if I add the ball after the for loop? -

the programme makes ball glide across top left bottom right , works. if shift line

frame.getcontentpane().add(ball);

from current position after loop, why doesn't ball show on frame. agree ball should no longer move, because shifting done in loop happens before add together ball jframe,but don't understand why ball doesn't show on screen when add together frame. here's code of working program, if shift line mentioned above after loop, ball no longer shows up

import java.awt.*; import javax.swing.*; import java.awt.event.*; public class animate { private jframe frame; private int x,y; public static void main(string args[]) { animate ballroll = new animate(); ballroll.go(); } public void go() { frame = new jframe(); frame.setsize(500,500); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); myroll ball = new myroll(); frame.getcontentpane().add(ball); for(x = 5;x<=350;x++) { y=x; seek { thread.sleep(50); } catch(exception e) { system.out.println("dsfsd"); } ball.repaint(); } } class myroll extends jpanel { public void paintcomponent(graphics g) { g.setcolor(color.black); g.fillrect(0, 0, this.getwidth(), this.getheight()); g.setcolor(color.orange); g.filloval(x, y, 100, 100); } } }

some points remember:

don't utilize thread.sleep() sometime hangs whole swing application instead seek swing timer suitable swing application.

read more how utilize swing timers

don't forget phone call super.paintcomponent() in overridden paintcomponent() method.

call frame.setvisible(true) in end after adding components.

use frame.pack() instead of frame.setsize(500,500) fits components per component's preferred size.

override getpreferredsize() set preferred size of jpanel in case of custom painting.

use swingutilities.invokelater() or eventqueue.invokelater() create sure edt initialized properly.

read more

why utilize swingutilities.invokelater in main method?

swingutilities.invokelater

should utilize eventqueue.invokelater gui update in java desktop application?

sample code: (change per custom painting)

private timer timer; ... timer = new javax.swing.timer(50, new actionlistener() { @override public void actionperformed(actionevent arg0) { y = ++x; ball.repaint(); if (x > 350) { timer.stop(); } } }); timer.setrepeats(true); timer.start(); public static void main(string args[]) { swingutilities.invokelater(new runnable() { @override public void run() { animate ballroll = new animate(); ballroll.go(); } }); } class myroll extends jpanel { @override protected void paintcomponent(graphics g) { super.paintcomponent(g); ... } @override public dimension getpreferredsize() { homecoming new dimension(..., ...); } }

java swing

No comments:

Post a Comment