【问题标题】:Accessing JButton[]访问 JButton[]
【发布时间】:2012-04-23 22:29:25
【问题描述】:

我在 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();
}
}

【问题讨论】:

  • 如何使用 JToggleButtons 将一行中的每个按钮添加到该行的 ButtonGroup 对象?
  • @HovercraftFullOfEels 你一针见血+1 :)
  • @HovercraftFullOfEels,一旦您将该评论作为答案,我将删除占位符答案。
  • @mre:谢谢,但不要删除您的答案。这是一个很好的答案,如果我没有我的评论,你可能会回答(我猜在你的答案发布之前你甚至没有看到我的评论)。 1+

标签: java arrays swing jbutton


【解决方案1】:

不要。你将重新发明轮子。使用JToggleButtons 并将它们按行分组到同一个ButtonGroup

@Hovercraft Full Of Eels 提出的建议是正确的(确实应该是一个答案)。

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    相关资源
    最近更新 更多