2010-11-21 64 views
0

我正在使用swing的GUI上工作。 我有一個主要的類,我最初加載兩個獨立的面板。我的第一個面板有一個textField和一個按鈕&第二個面板,它是嵌入在面板中的網格佈局,如9個按鈕,編號爲A1,A2,A3,... A9。 所以正如我所說,這些都是最初從我的主類加載。在運行時GridLayout面板按鈕文本更新

現在執行後,因爲我看到我的獨立panels.Now從面板1(其中有文本字段和按鈕)我把一些文本,如A1號。我想要的是第二個面板上按鈕的顏色應該改變。

我做了什麼,我添加了一個ActionListiner到firstPanel上的按鈕,並創建了第二個Panel的新實例。但是這樣Panel 2重複。所以當我繼續在textField中添加數字時,我看到了新面板。我如何才能在運行時更新現有的第二個面板按鈕顏色?

回答

1

我想你有類似

JPanel panel2 = new JPanel(new GridLayout(3,3)); 
JButton[] buttons = new JButton[9]; 

// instantiate buttons and add them to grid panel 
for (int i = 0; i < 9; ++i) { 
    buttons[i] = new JButton("A"+(i+1)); 
    panel2.add(buttons[i]); 
} 

.... 

void actionPerformed(ActionEvent e) { 
    String text = ((JTextField)e.getSource()).getText(); 

    //simplified, I assume input is always correct and in the form of "An" where n is the digit 
    // convert the string to an index to reference the correct button in array 
    int which = Integer.parseInt(text.substring(1,2)); 

    buttons[which].setBackground(Color.RED); 
} 
相關問題