swing - Java run+repaint = grey window -
i'm trying play around jframe/jpanels repaint();
, forth, when start thread, , call repaint via run while true, spits out line of system.out.println("as");
put in place check if loop running.
so question is: why drawings disappearing when calling repaint in loop? (it seems jframe
canvas_width
/height
showing up, no panels etc.)
public static void main(string[] args) { jframe frame = new jframe(); frame.setsize(canvas_width, canvas_height); frame.setpreferredsize(new dimension(canvas_width, canvas_height)); frame.setvisible(true); frame.setresizable(false); frame.setdefaultcloseoperation(jframe.exit_on_close); jpanel p = new jpanel(new gridlayout()); frame.getcontentpane().add(p); s = new something(); p.add(s); p.setbackground(color.black); frame.pack(); }
and class:
public class extends jpanel implements runnable { public something(){ thread t = new thread(); t.start(); run(); } @override public void paintcomponent(graphics g){ super.paintcomponent(g); g.setcolor(color.cyan); g.fillrect(0, 0, getwidth()-150, getheight()-100); g.setcolor(color.black); g.filloval(10, 10, 25, 25); } @override public void run() { while(true){ repaint(); system.out.println("as"); try { thread.sleep(1); } catch (interruptedexception e){} } } }
any regarding contentpane
appreciated, since, i'm not sure done correctly.
instead of calling thread.sleep(n)
in thread
, implement swing timer
repeating tasks. ensures repaint()
called on event dispatch thread.
see concurrency in swing more details.
also, repainting every 1 millisecond being optimistic.
working sscce e.g. (note version changes co-ords of resulting paint operations, know happening!
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class extends jpanel { static final int canvas_width = 400; static final int canvas_height = 100; private int xdelta = 0; public something(){ actionlistener animater = new actionlistener() { @override public void actionperformed(actionevent ae) { repaint(); } }; timer t = new timer(10,animater); t.start(); } @override public void paintcomponent(graphics g){ super.paintcomponent(g); g.setcolor(color.cyan); g.fillrect(0, 0, getwidth()-(xdelta--), getheight()-100); g.setcolor(color.black); g.filloval(xdelta, 10, 25, 25); if (xdelta<0) { xdelta = canvas_width; } } @override public dimension getpreferredsize() { return new dimension(canvas_width, canvas_height); } public static void main(string[] args) { jframe frame = new jframe(); frame.setdefaultcloseoperation(jframe.exit_on_close); jpanel p = new jpanel(new gridlayout()); frame.getcontentpane().add(p); s = new something(); p.add(s); p.setbackground(color.black); frame.pack(); frame.setresizable(false); frame.setvisible(true); } }
Comments
Post a Comment