2011-07-16 11 views
3

Iは、下部に上部のそれぞれに...スイングインターフェイス内のすべてのボタンを反復処理する方法は?

JFrame frame = new JFrame("my 3x3"); 
    JPanel panel = new JPanel(); 
    Container pane = frame.getContentPane(); 
    panel.setLayout(new GridLayout(3,3)); 
    panel.add(upperLeft); 
    panel.add(upperCenter); 
    panel.add(upperRight); 
    panel.add(midLeft); 
    panel.add(midCenter); 
    panel.add(midRight); 
    panel.add(bottomLeft); 
    panel.add(bottomCenter); 
    panel.add(bottomRight); 
    pane.add(panel); 

このコードを使用して、ボタンの3×3グリッドのフレームを作成したが、JButtonのオブジェクトである右の要素に左。

後で実行するには、これらのボタンのリストを反復してリセットする必要がありますが、その時点ではすべてがフレームです。私はフレームオブジェクトのどこかに埋もれていることは分かっていますが、コンポーネントのリストはおそらく深い層ですが、どこですか?フレームのボタンを取得する簡単な方法はありますか?

答えて

3

各スイングContainergetComponents()です。したがって、JFrame(またはそのgetContentPane())から、再帰的に下に移動してすべてのコンポーネントを取得できます。

ただし、ボタンをパネルに追加すると、List<JButton>を保持することができます。

2

ボタンのグリッドは3x3なので、事前に(プログラムが実行される前に)これを知っているので、2次元の3x3ボタンの配列を作成しないでください。次にボタンのインデックスはその位置を自然に反映します。

編集:例については

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

@SuppressWarnings("serial") 
public class ButtonGridGuiPanel extends JPanel { 
    // The number of rows and columns 
    private static final int MAX_ROWS = 3; 
    private static final int MAX_COLS = MAX_ROWS; 

    // the size of the button text in "points" 
    private static final float BTN_PTS = 64; 

    // starting text for button. Has spaces so button isn't too narrow 
    private static final String INITIAL_TEXT = " "; 

    // The 2-D JButton array that holds our buttons 
    private JButton[][] buttonGrid = new JButton[MAX_ROWS][MAX_COLS]; 
    private int buttonPressCount = 0; 

    public ButtonGridGuiPanel() { 
     JPanel buttonGridPanel = new JPanel(); // jpanel to hold the buttons 
     buttonGridPanel.setLayout(new GridLayout(MAX_ROWS, MAX_COLS)); 

     // create an action listener to add to all buttons 
     ButtonListener btnListener = new ButtonListener(); 

     // iterate through the 2-d button array 
     for (int row = 0; row < buttonGrid.length; row++) { 
     for (int col = 0; col < buttonGrid[row].length; col++) { 
      // create a new button with blank text 
      JButton btn = new JButton(INITIAL_TEXT); 
      // set its font 
      btn.setFont(btn.getFont().deriveFont(Font.BOLD, BTN_PTS)); 
      // add the action listener 
      btn.addActionListener(btnListener); 
      buttonGridPanel.add(btn); // add button to the JPanel 
      buttonGrid[row][col] = btn; // and add it to the 2-d array 
     } 
     } 

     JButton resetButton = new JButton("Reset"); 
     resetButton.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      reset(); // call the reset method, that's it! 
     } 
     }); 
     JPanel resetBtnPanel = new JPanel(); // to hold reset button 
     resetBtnPanel.add(resetButton); 

     setLayout(new BorderLayout()); // main JPanel uses border layout 
     add(buttonGridPanel, BorderLayout.CENTER); // add button grid panel to main 
     add(resetBtnPanel, BorderLayout.PAGE_END); // add reset btn panel to main 
    } 

    public void reset() { 
     buttonPressCount = 0; // in order that first press gives "X" 

     // then iterate through the button grid's rows and columns 
     // setting button text back to its initial state 
     for (int row = 0; row < buttonGrid.length; row++) { 
     for (int col = 0; col < buttonGrid[row].length; col++) { 
      buttonGrid[row][col].setText(INITIAL_TEXT); 
     } 
     } 
    } 

    // a simple action listener that finds out which button has been pressed 
    // and sets the button's text alternatingly to "X" or "O" 
    private class ButtonListener implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
     JButton btn = (JButton)e.getSource(); // get pressed button 
     String text = btn.getText().trim(); // get its text 
     if (text.isEmpty()) { // if text is blank 

      // iterate through the 2d button array to find out the 
      // row and col position of the pressed button 
      int rowPressed = -1; 
      int colPressed = -1; 
      for (int row = 0; row < buttonGrid.length; row++) { 
       for (int col = 0; col < buttonGrid[row].length; col++) { 
        if (btn == buttonGrid[row][col]) { 
        // button has been found! 
        rowPressed = row; 
        colPressed = col; 
        } 
       } 
      } 
      // make the button text alternate between X and O 
      text = (buttonPressCount % 2 == 0) ? "X" : "O"; 
      btn.setText(text); // set the button's text 
      buttonPressCount++; 

      // TODO: perform whatever logic is necessary based on the row 
      // and column position of the button 
      System.out.printf("[row, col]: [%d, %d]%n", rowPressed, colPressed); 
     } 

     } 
    } 

    private static void createAndShowUI() { 
     JFrame frame = new JFrame("Button Grid"); 
     frame.getContentPane().add(new ButtonGridGuiPanel()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     // create the GUI in a thread-safe manner 
     java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowUI(); 
     } 
     }); 
    } 
} 
+0

@dacracot:例えば編集を参照してください... –

+0

編集2:コメントは –

+0

@dacracotを追加しました:編集3:追加のリセット機能とちょうどことないボタン。 –

関連する問題