2012-04-11 10 views
3

私は3つの行に3つのボタンがあります:緑、黄、赤。彼らはすべて自分の配列に入っています。
緑のボタンをクリックすると、同じ行の他の2つのボタンが無効になります。しかし、私はどのように配列を使ってそれを処理するか分からない。JButton []へのアクセス

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(); 
} 
} 
+6

行の各ボタンがその行のButtonGroupオブジェクトに追加された状態でJToggleButtonsを使用するとどうなりますか? –

+0

@HovercraftFullOfEelsあなたは頭の上の釘を打つ+1: – fireshadow52

+0

@HovercraftFullOfEels、あなたがそのコメントに答えるとすぐに、私はプレースホルダーの答えを削除します。 – mre

答えて

6

Do not。あなたは車輪を再発明するでしょう。 JToggleButtonを使用し、すべてを同じ行単位で同じButtonGroupにグループ化します。

@Hovercraft Full Of Eelsによって提案されたのは、スポットライトです(本当に答えが必要です)。