java - Itterating through a list and drawing a colored square -
where begin...........
i have colored box, want change color every 1/2 second, want code run well.
i'm using java awt's graphic api draw using g.fillrect(568, 383, 48, 48); g wrapped 'graphics.'
so you'd think simple right?
color[] colors colors = new color[4]; colors[0] = new color(color.red); colors[1] = new color(color.blue); colors[2] = new color(color.green); colors[3] = new color(color.yellow); for(int = 0; < colors.length; i++){ g.setcolor(colors[i]); g.fillrect(568, 383, 48, 48); }
this cool problem none of program runs when loop running...
i think can make game 'multi-threaded' means can more 1 thing @ time have no idea how , sounds hard, appreciated!
thanks reading!
most ui frameworks aren't thread safe, need beware of that. example, in swing, use swing timer
act pseudo loop. because timer
notifies actionlistener
within context of event dispatching thread, makes safe update ui or state of ui within, without risking thread race conditions
take @ concurrency in swing , how use swing timers more details
import java.awt.color; import java.awt.dimension; import java.awt.eventqueue; import java.awt.graphics; import java.awt.graphics2d; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.timer; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; public class javaapplication430 { public static void main(string[] args) { new javaapplication430(); } public javaapplication430() { eventqueue.invokelater(new runnable() { @override public void run() { try { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) { ex.printstacktrace(); } jframe frame = new jframe("testing"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.add(new testpane()); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } }); } public class testpane extends jpanel { private color[] colors; private int whichcolor = 0; public testpane() { colors = new color[4]; colors[0] = color.red; colors[1] = color.blue; colors[2] = color.green; colors[3] = color.yellow; timer timer = new timer(500, new actionlistener() { @override public void actionperformed(actionevent e) { whichcolor++; repaint(); if (whichcolor >= colors.length) { whichcolor = colors.length - 1; ((timer)(e.getsource())).stop(); } } }); timer.start(); } @override public dimension getpreferredsize() { return new dimension(200, 200); } @override protected void paintcomponent(graphics g) { super.paintcomponent(g); graphics2d g2d = (graphics2d) g.create(); g2d.setcolor(colors[whichcolor]); g2d.fillrect(0, 0, getwidth(), getheight()); g2d.dispose(); } } }
Comments
Post a Comment