I have just recently gotten into Java and am a still a noob. I have created a 9x9 panel of JPanels using a for loop to add the buttons. How would I create an action listener that would allow me to choose different colors that will appear as the background color of the JButton when clicked? I'm trying to make a miniature pixel art program.
It will look something like this. In this example, [row] and [col] refer to the row and column values of your grid. Be sure to create counter (private static int counter = 0;). or else you will get a bunch of errors. Here is the Code:
JBut[row][col].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
typeOfButton button = (typeOfButton) e.getSource();
int row = button.getRow();
int col = button.getCol();
counter++;
if (counter == 1) {
JBut[row][col].setBackground(Color.RED);
}
else if (counter == 2) {
JBut[row][col].setBackground(Color.ORANGE);
}
else if (counter == 3) {
JBut[row][col].setBackground(Color.YELLOW);
}
else if (counter == 4) {
JBut[row][col].setBackground(Color.GREEN);
}
else if (counter == 5){
JBut[row][col].setBackground(Color.BLUE);
}
else if (counter == 6){
JBut[row][col].setBackground(Color.MAGENTA);
}
else {
JBut[row][col].setBackground(Color.BLACK);
counter = 0; //makes color cycle repeat, starting with red
} //end else
} //end actionPerformed
}); //end ActionListener
Obviously, the simple way to do this would be to put the giant if statement in a new method called determineColor() or something like that.