2017-03-17 60 views
-2

我正在學校項目中工作,我正在使用NetBeans IDE。在這個項目中,我的程序有很多使用相同代碼的按鈕,但名稱不同。不是每次都重新輸入變量名稱,有沒有辦法調用按鈕本身的名稱?如何調用Jbutton的變量名稱

sa1++; 
    if(sa1 % 2 == 0) { 
     A1.setEnabled(true); 
     A1.setBackground(Color.green); 
     A1.setOpaque(false); 
    } 
    else { 
     A1.setEnabled(false); 
     A1.setBackground(Color.red); 
     A1.setOpaque(true); 
    } 

請注意,按鈕下去字母高達5而不是重新鍵入它,有沒有辦法把它想:

[JButton的變量名稱] .setEnabled(真);

爲什麼需要更少的時間?

我的老師對此很好奇 ,這對未來的項目也有幫助。 編輯:老師知道如何做到這一點,我的意思是他想看看我怎麼弄出來。你們有點苛刻,不是嗎?

+3

好像現在要做的正確的最好的辦法是找到一個新的類有一位新老師。 – csmckelvey

+0

你做了什麼研究。老師不知道如何解決這個問題應該讓人擔心,因爲通過基本培訓對Java的基本理解解決了所有問題的答案。 – Underbalanced

+0

雷電塔基,我們是好人:)。無論如何,這只是你寫錯了方式。然而,編輯這個問題現在一切都很有意義。希望提供的答案能幫助你。祝你進入java的旅程順利。 :)。 –

回答

2

將在陣列的按鈕:這樣

buttons[0] = new JButton(); 
//add any other initialization, like event handlers 

然後循環通過它們:

//change the 5 to however many buttons you want to have 
JButton[] buttons = new JButton[5]; 

然後初始化它們

for (int i = 0; i < buttons.length; i++) { 
    //replace the line below with whatever you want to do with each button 
    performSomeAction(buttons[i]); 
} 

與下面的另一個很好的答案結合這一點,您還可以封裝你想要做的按鈕,一切的方法:

private void performSomeAction(JButton button) { 
    if(sa1 % 2 == 0) { 
     button.setEnabled(true); 
     button.setBackground(Color.green); 
     button.setOpaque(false); 
    } 
    else { 
     button.setEnabled(false); 
     button.setBackground(Color.red); 
     button.setOpaque(true); 
    } 
} 
0

將它們添加到List並執行foreach循環。

1

在這個項目中,我的程序有很多按鈕使用相同的代碼, 但名稱不同。每次都不要重新輸入變量名稱 ,有沒有辦法調用按鈕本身的名稱?

將其重構爲一種方法。

實施例:

public void TestMethod(JButton button) 
    if(sa1 % 2 == 0) { 
     button.setEnabled(true); 
     button.setBackground(Color.green); 
     button.setOpaque(false); 
    } 
    else { 
     button.setEnabled(false); 
     button.setBackground(Color.red); 
     button.setOpaque(true); 
    } 
} 

然後,只需每次調用​​的方法和傳遞的相應按鈕參考。

實施例:

TestMethod(A1); 
TestMethod(A2); 
TestMethod(A3); 
TestMethod(A4);