访问JButton []

use*_*330 3 java arrays swing jbutton

我有3行3个按钮:绿色,黄色和红色.它们都在一个自己的阵列中.
单击绿色按钮时,同一行中的其他2个按钮将被禁用.但我不知道如何使用数组来处理它.

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();
}
}
Run Code Online (Sandbox Code Playgroud)

mre*_*mre 6

别.你将重新发明轮子.使用JToggleButtons并将它们全部分组到ButtonGroup每行中.

@Hovercraft Full Of Eels提出的建议是现货(并且应该是一个答案).