Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JButton[]

I have 3 buttons in 3 rows: green, yellow and red. They all are in an own array.
When I click a green button, the other 2 buttons in the same row should become disabled. But I'm not sure how to handle it using arrays.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame implements ActionListener {

View view = new View();
JButton bGreen[] = new JButton[3];
JButton bYellow[] = new JButton[3];
JButton bRed[] = new JButton[3];

public Test() {
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setBounds(300, 100, 500, 400);
    this.setVisible(true);
    this.setLayout(new GridLayout(3, 3));

    makeButtons();
}

public void makeButtons() {
    for (int i = 0; i < 3; i++) {
        bGreen[i] = new JButton("Green");
        bYellow[i] = new JButton("Yellow");
        bRed[i] = new JButton("Red");

        bGreen[i].setBackground(Color.green);
        bYellow[i].setBackground(Color.yellow);
        bRed[i].setBackground(Color.red);

        bGreen[i].addActionListener(this);
        bYellow[i].addActionListener(this);
        bRed[i].addActionListener(this);

        this.add(bGreen[i]);
        this.add(bYellow[i]);
        this.add(bRed[i]);
    }
}

@Override
public void actionPerformed(ActionEvent ae) {
    Object source = ae.getSource();
    if (source == bGreen) // e.g. bGreen[1]
    {
        // bYellow[1].setEnabled(false);
        // bRed[1].setEnabled(false);
    }
    if (source == bYellow) // e.g. bYellow[1]
    {
        // bGreen[1].setEnabled(false);
        // bRed[1].setEnabled(false);
    }
    // the same with bRed
}

public static void main(String[] args) {
    Test test = new Test();
}
}
like image 639
Evgenij Reznik Avatar asked Mar 08 '26 19:03

Evgenij Reznik


1 Answers

Don't. You'll be re-inventing the wheel. Use JToggleButtons and group them all into the same ButtonGroup on a per-row basis.

The suggestion made by @Hovercraft Full Of Eels is spot-on (and should really be an answer).

like image 89
mre Avatar answered Mar 11 '26 08:03

mre