2014-07-22 95 views
-2

我正在做一個戰艦遊戲,我是Java主題的新手。爲了創建100個JButton,我做了一個嵌套循環的網格佈局,但在嘗試向所有按鈕添加一個動作偵聽器時遇到困難。有人可以幫我一把嗎?Java動作監聽器嵌套循環

我稍後會發布代碼:)

乾杯傢伙。

enter code here 
public Center_Panel() { 
    this.setLayout(new GridLayout(1,2)); 
    JPanel panel1 = new JPanel(new GridLayout(10, 10)); 
    panel1.setBackground(Color.BLUE); 

    for (int i = 0; i < 10; i++) { 
     for (int j = 0; j < 10; j++) { 
     JButton button = new JButton(Integer.toString(i + + j)); 
     panel1.add(button); 
     } 
     //grid [i][j] = b; 
    } 

    this.add(panel1); 

    JPanel panel2 = new JPanel(new GridLayout(10, 10)); 

    panel2.setBackground(Color.GREEN); 
    for (int i = 0; i < 10; i++) { 
     for (int j = 0; j < 10; j++) { 
     JButton button = new JButton(Integer.toString(i + + j)); 
     panel2.add(button);} 
+0

你有什麼困難?究竟是什麼問題? –

+1

您可以在創建按鈕時添加偵聽器(在循環中)。如果你發佈了一些代碼,它會更容易幫助你。 – Anton

+0

你想添加相同的偵聽器到所有按鈕?也請在你的問題下添加你的代碼,以便我們看到你想要做什麼。 – danizmax

回答

1

將JButton聲明爲for循環,然後將它們初始化爲for循環。 您需要爲JButton創建一個數組,您將不同的字符串分配給同一個引用。

此代碼用於創建JButton並將它們添加到面板。

JButton button[] = new JButton [100]; 
int count = 0; 
for (int i = 0; i < 10; i++) { 
    for (int j = 0; j < 10; j++) { 
     button[count] = new JButton(Integer.toString(i + + j)); 
     panel1.add(button); 
     count++; 
     } 
} 

此代碼將它們添加到動作偵聽器。

for (int x = 0; x < 100; x++) { 
    button[x].addActionListener(this); 
} 
+0

我已更改代碼 –

+0

感謝您的時間,它工作:) –

+0

@ma_nafx不客氣 –