2016-12-05 74 views
-1
public void createButton(int x, int y, String s) { 
    try { 
     JButton btn1 = new JButton(); 
     jPanel1.add(btn1); 
     btn1.setLocation(x, y); 
     btn1.setSize(50, 50); 
     btn1.setVisible(true); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     System.out.println(e); 
    } 
} 

這就是我用來創建隨機按鈕的方法。但是我不能每次都手動給這個按鈕起個名字。我想用我的String變量包含的名稱按鈕對象。如何將Button對象命名爲String變量帶來的效果

+1

把String's'傳遞給JButton的構造函數。 – yogidilip

+0

我可以寫什麼? – Silver

+2

請勿發佈您的代碼圖片。將實際代碼複製到您的問題中,每行縮進四個空格,以便顯示爲格式化的塊。 – VGR

回答

3

從另一個回答您的評論:

我並不想要改變按鈕name.i想按鈕變量名(在這種情況下,BTN1)什麼字符串s帶來的變化。

的Java不是這樣設計的,如果你想保持每個JButton一個參考,你可以創建一個數組:

JButton buttonsArray[] = new JButton[5]; //Or any amount of buttons 

然後使用它們像這樣:

for (int i = 0; i < buttonsArray.length; i++) { 
    buttonsArray[i] = createButton(text[i]); 
} 

在哪裏text[i]是一個String數組,其中包含您的所有文本JButton s

或很可能與ArrayListJButton的:

ArrayList <JButton> buttonsList = new ArrayList <JButton>(); 

,然後用它喜歡:

for (int i = 0; i < text.length; i++) { 
    JButton button = createButton(text[i]); 
    buttonList.add(button); 
} 

然後你可以選擇與每個按鈕:

buttonArray[i].setText("Hello"); //Or whatever method you want to call 
buttonList.get(i).setText("Hello"); 
jPanel1.add(buttonsArray[i]); 
jPanel1.add(buttonsList.get(i)); 

現在你createButton()方法應該看像這樣:

public JButton createButton(String s) { 
    JButton btn1 = new JButton(s); 
    //Add more code here 
    return btn1; 
} 

在這個問題上,你可以使用JRadioButton


重要注意數組

最後,我需要它添加到我的回答看到一個類似的例子,不設置每個JComponent的位置/界限請手動使用適合您的作業Layout ManagerEmpty Borders以在需要時在它們之間創建空間。

我敢打賭,你使用的是null佈局,而似乎是最好的和最簡單的方法來創建一個圖形用戶界面,爲您創造更多的圖形用戶界面,你會得到由於這種更多的錯誤,更麻煩試圖保持它。

參見:Null layout is evilWhy is it frowned upon to use a null layout in swing?

我希望能幫到

+0

謝謝你looooooot爲你的幫助我的朋友。這是exatelly我需要:) – Silver

+0

@銀器我很高興它的幫助,不要忘記[接受](http://stackoverflow.com/help/accepted-回答)答案:) – Frakcool

2
public void createButton(int x, int y, String s) { 
    try { 
     JButton btn1 = new JButton(s); 
     jPanel1.add(btn1); 
     btn1.setLocation(x, y); 
     btn1.setSize(50, 50); 
     btn1.setVisible(true); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     System.out.println(e); 
    } 
} 

構造JButton(text)內部調用setText(text)。所以後面的btn1.setText(text)也是一樣的。從代碼:

/** 
* Creates a button with initial text and an icon. 
* 
* @param text the text of the button 
* @param icon the Icon image to display on the button 
*/ 
public JButton(String text, Icon icon) { 
    // Create the model 
    setModel(new DefaultButtonModel()); 

    // initialize 
    init(text, icon); 
} 

記住:setText()setName()是不一樣的東西!

+0

我不想要更改按鈕name.i想要按鈕變量名稱(在這種情況下它是btn1)更改爲什麼字符串帶來。 – Silver

相關問題