2011-07-16 63 views
3

我已經創建了使用此代碼的按鈕的3×3網格中的幀...如何遍歷Swing界面中的所有按鈕?

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); 

...,每個上的降低,從左至右元件是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:增加了復位功能和一個按鈕,做到了這一點。 –