I am trying to create this simple GUI where the number of clicks is displayed on the button and incremented after each click, and so that after each click, the colours of each button are rotated one value to the right. At the moment, the GUI is created, but the background is not set and nothing happens when you click on anything. I can't seem to find a problem here. Can anyone see any ?
Thanks a lot for your help with this :)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ButtonJava extends JButton implements ActionListener {
private static int currentColor=0;
private int clicks;
private static final Color[] COLORS = {
Color.ORANGE,
Color.WHITE,
Color.GREEN };
public ButtonJava( ){
setBackground( Color.YELLOW );
setText( "Pick ME" );
this.addActionListener( this );
}
public static void main(String[] args) {
JFrame frame = new JFrame ("JFrame");
JPanel panel = new JPanel( );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
JButton buttons[] = new JButton[3];
for(int i = 0;i<buttons.length ; i++){
buttons[i] = new ButtonJava();
panel.add(buttons[i]);
}
frame.getContentPane( ).add( panel );
frame.setSize( 500, 500);
frame.setVisible( true );
}
private void updateButton() {
changeColors();
clicks++;
setText( "# of clicks = " + Integer.toString(clicks) );
}
private void changeColors( ) {
for (int i=0;i<COLORS.length;i++){
setBackground(COLORS[currentColor]);
currentColor %=2;
}
}
@Override
public void actionPerformed( ActionEvent event ) {
updateButton( );
}
}
ButtonJavaobject only has control of itself, which means when you click on one of the buttons, only that button will change color. If you want to click on one of the buttons and have ALL of the buttons change color, you're going to have to provide the other buttons to each button's constructor, and then havechangeColorcallsetBackgroundon each of the other buttons.ButtonJava. One way of doing this is to have yourButtonJavaconstructor take a list ofJButton(orButtonJava), and then inchangeColoryou would iterate over that list of buttons and callsetBackgroundon each one.