btrballin
btrballin

Reputation: 1464

Java Swing grid of buttons with individual control

So I know how a grid of buttons are made, but what happens from the implementation is that once the button is added into the frame/panel, you can't refer to it as a JButton object. My question is once I create a grid full of buttons and add them into the panel, how would I change the button background or border when they are clicked?

public GridTest(int rows, int cols) {
Container pane = getContentPane();
pane.setLayout(new GridLayout(rows, cols));
String[] labels = {"A", "B", "C"};
for (int i = 0; i < labels.length; i++) {
  JButton button = new JButton(labels[i]);
  pane.add(button);
    }
}

How would I set the background of button with the "A" label to red when it is clicked on?

if ("A".equals(actionCommand)) {...}

Upvotes: 0

Views: 93

Answers (2)

Leet-Falcon
Leet-Falcon

Reputation: 2147

If you intend to act on click events to modify the source button, then the best practice is also the simplest:
Use ActionListener:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        AbstractButton btnSource = ((AbstractButton)e.getSource());
        // handle btnSource 
    }
});

If you intend to modify other components as well, you can always add them to an internal container (e.g: ArrayList) and group them up into a logical unit.
You could then react on that logical unit as you require.

Upvotes: 0

Tomasito665
Tomasito665

Reputation: 1209

You can loop through all the components in the pane and (if possible) cast them to JButton.

for (Component c : pane.getComponents()) {
    if (c instanceof JButton) {
        JButton b = (JButton) c;
        // Now you can do whatever you want with b.
        // For example: b.setBackground(Color.red)
    }
}

Upvotes: 1

Related Questions