Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your while loop is stopping the repaint manager from ever getting around to changing the colors.</p> <p>You need to, some how, execute the request in the background, something like this</p> <pre><code>public class TestLabel extends JLabel { private Timer timer; private int r = 0; private int g = 155; private int b = 12; public TestLabel() { setText("Hello world"); setOpaque(true); timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("tick"); r = (r + 1) % 255; g = (g + 1) % 255; b = (b + 1) % 255; Color color = new Color(r, g, b); setBackground(color); System.out.println(color); if (r == 0 &amp;&amp; b == 0 &amp;&amp; g == 0) { r = 0; g = 155; b = 12; } invalidate(); revalidate(); repaint(); } }); timer.setRepeats(true); timer.setCoalesce(true); timer.start(); } } </code></pre> <p>You might like to read up on</p> <ul> <li><a href="http://www.google.com.au/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;ved=0CFIQFjAA&amp;url=http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html&amp;ei=WZclUM9mppyIB8vFgLAB&amp;usg=AFQjCNEV-IbRLqmbImNIyRXEWy5L7ZP9tw&amp;sig2=VlMYjPURnV_J4TwKUbT7cw" rel="nofollow">The Event Dispatching Thread</a></li> <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html" rel="nofollow">Concurrency in Swing</a></li> </ul> <p><strong>UPDATED with Extended Example</strong></p> <pre><code>public class TestLabel extends JLabel { private Timer timer; private Object[][] colors = {{"Black", Color.BLACK}, {"Blue", Color.BLUE}, {"Cyan", Color.CYAN}, {"Dark Gray", Color.DARK_GRAY}, {"Gray", Color.GRAY}, {"Green", Color.GREEN}, {"Light Gary", Color.LIGHT_GRAY}, {"Mangenta", Color.MAGENTA}, {"Orange", Color.ORANGE}, {"Pink", Color.PINK}, {"Red", Color.RED}, {"White", Color.WHITE}, {"Yellow", Color.YELLOW}}; public TestLabel() { setText("Hello world"); setOpaque(true); timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("tick"); int index = (int) Math.round((colors.length - 1) * Math.random()); Object[] group = colors[index]; setBackground((Color)group[1]); setText((String)group[0]); } }); timer.setInitialDelay(0); timer.setRepeats(true); timer.setCoalesce(true); timer.start(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload