public class ButtonWindow extends JFrame implements Runnable { private JPanel topPanel = new JPanel(new GridBagLayout()); JButton[] listButtons = new JButton[5]; private Thread t; public void run() { System.out.println("Running thread"); try { for(int i = 1; i < listButtons.length; i++) { System.out.println("Thread changing colors"); listButtons[i].setBackground(Color.YELLOW); Thread.sleep(1000); listButtons[i].setBackground(Color.ORANGE); Thread.sleep(1000); listButtons[i].setBackground(Color.RED); Thread.sleep(1000); listButtons[i].setBackground(null); } } catch (InterruptedException e) { System.out.println("Thread interrupted."); } System.out.println("Thread closing."); }//close run() method public void start(){ System.out.println("Starting thread "); if(t == null){ t = new Thread(this); t.start(); } }//close start() method //CONSTRUCTOR public ButtonWindow(){ //create the buttons for(int i = 0; i < 5; i++){ listButtons[i] = new JButton(String.valueOf(i)); } setSize(400,400); setTitle("Colors"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); buildTopPanel(); //BUTTON LISTENERS///////////////////////////////////////////////////////////////////////////////// listButtons[0].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { System.out.println("Creating thread"); start(); } }); //BUTTON LISTENERS END/////////////////////////////////////////////////////////////////// }//CLOSE CONSTRUCTOR //CREATE PANEL public void buildTopPanel(){ GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; for(int i = 0; i < 5; i++){ //listButtons[i] = new JButton(String.valueOf(i)); gc.insets = new Insets(5, 10,0,0); topPanel.add(listButtons[i],gc); gc.gridy ++; } add(topPanel,BorderLayout.NORTH); } }//CLOSE CLASSS
t
null
start
run
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)