首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问JButton[]

访问JButton[]
EN

Stack Overflow用户
提问于 2012-04-11 23:22:21
回答 1查看 773关注 0票数 3

我有三个按钮,三排:绿色,黄色和红色。它们都在自己的数组中。

当我单击一个绿色按钮时,同一行中的其他两个按钮应变为禁用状态。但是我不确定如何使用数组来处理它。

代码语言:javascript
复制
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();
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-11 23:27:17

不要,你会重新发明轮子的。使用JToggleButton,并以行为单位将它们全部分组到同一个ButtonGroup中。

@Hovercraft Full Of Eels提出的建议很中肯(而且应该是一个真正的答案)。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10108972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档