View Single Post
  #2 (permalink)  
Old 09-22-2007, 01:22 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
Code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColourPanel extends JPanel implements Runnable { public void run() { try { for (int i=0; i<10; i++) { randomNumber = Math.random(); if ((randomNumber >= 0) && (randomNumber < 0.25)) setBackground(Color.RED); if ((randomNumber >= 0.25) && (randomNumber < 0.5)) setBackground(Color.BLUE); if ((randomNumber >= 0.5) && (randomNumber < 0.75)) setBackground(Color.MAGENTA); if ((randomNumber >= 0.75) && (randomNumber <= 1)) setBackground(Color.ORANGE); repaint(); System.out.printf("i = %s isDisplayable = %b%n", i, isDisplayable()); Thread.sleep(200); } } catch (InterruptedException e) { return; } } public ColourPanel() { setLayout(new BorderLayout()); colourButton = new JButton("Change Background"); add(colourButton, BorderLayout.SOUTH); colourButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // This first line creates a new instance of ColourPanel // which is not the current instance that has been // instantiated and loaded into a gui. So this new // instance runs just fine but cannot be seen. //Runnable q = new ColourPanel(); // If you get a reference to the current instance // that has been instantiated and added to a gui // you will see the colors change. Since we are inside // another class ("this" == this ActionListener anonymous // class) we use the static form of obtaining a reference. Runnable q = ColourPanel.this; Thread s = new Thread(q); s.start(); } }); } public static void main(String[] args) { ColourPanel panel = new ColourPanel(); panel.setPreferredSize(new Dimension(200,200)); JOptionPane.showMessageDialog(null, panel, "", -1); } private JButton colourButton; private double randomNumber; }
Reply With Quote