I'm trying to add 10 buttons to a JPanel one by one, and then adding them all to a JFrame. I need to have my for loop because it has to be easy changing the number of buttons. All the buttons also need to have different colors and texts (I know that they CAN get the same color with the code below, but that's OK for now).
My output from the code below is just a frame with 10 white buttons and no text/color. Why is the colors, text and the actionlistener not getting connected to my buttons?
I've read on other questions that I have to be careful of my placements regarding frame.add(panel, frame.pack() and frame.setVisible(true), but I think these are correctly placed outside of my forloop. I also tried using frame.setContentPane(panel), but this gave the same result - a frame with 10 white buttons and no text/color.
CMain class:
public class CMain extends MyButton {
public static void main(String[] args) {
Random randomGenerator = new Random();
int numberofbuttons = 10;
JPanel panel = new JPanel();
JFrame frame = new JFrame("MyButton testing");
for (int i = 0; i < numberofbuttons; i++) {
float r = randomGenerator.nextFloat();float g = randomGenerator.nextFloat();float b = randomGenerator.nextFloat();float r2 = randomGenerator.nextFloat();float g2 = randomGenerator.nextFloat();float b2 = randomGenerator.nextFloat();
String theText = "SWITCH ME BACK";
String theOtherText = "button nr: " + i;
Color theColor = new Color(r, g, b);
Color theOtherColor = new Color(r2, g2, b2);
MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);
panel.add(myb);
}
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
MyButton class:
public class MyButton extends JButton implements ActionListener {
private JButton button;
private Color col1;
private Color col2;
private String text1;
private String text2;
public MyButton(Color col1, Color col2, String text1, String text2) {
this.col1 = col1;
this.col2 = col2;
this.text1 = text1;
this.text2 = text2;
button = new JButton(text1);
button.setOpaque(true);
button.setBackground(col1);
button.addActionListener(this);
}
public MyButton() {
this(Color.blue, Color.red, "click = make red", "click = reset to blue");
}
public void ToggleState() {
Color initialBackground = button.getBackground();
if (initialBackground == col1) {
button.setBackground(col2);
button.setText(text2);
} else if (initialBackground == col2) {
button.setBackground(col1);
button.setText(text1);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
this.ToggleState();
}
}
}