This is just a little code snippet containing a little trick I used today to build a simple button that switches between panel colors.
[NOTE: This might not be the best method. If you have a better way of doing it, please reply.]
//Declarations for the variables used below int option = 0; //Variable used to select colors final Color[] colors = {Color.ORANGE, Color.BLUE, Color.CYAN, Color.RED, Color.GREEN, Color.YELLOW, Color.MAGENTA}; //Our Color array. public void actionPerformed(ActionEvent e) { option++; //Increment this variable each time we click the button if(option>colors.length-1) option = 0; //Check if it has reached the end of the array. //If it has, reset the variable option. myPanel.setBackground(colors[option]); //Update colors. myPanel2.setBackground(colors[option]); }
So what this should do is everytime you click the button, the option variable increments. Then it sets the background of the 2 panels to one of the values in color[], where the index is the new value of option. If it becomes greater than the amount of elements in option (-1), It resets the option variable back to 0. This method is handy, so all you have to do to add more colors is to add more elements to the array.
Again, there could be other methods better than this, so feel free to post if you have an easier way.
EDIT: Just a note to some people wondering why I use colors.length-1 instead of colors.length. If you use colors.length, It will work fine, but it shows errors in the console. Use colors.length-1 to avoid the errors.