我一直在試圖弄清楚如何製作一個基於數組內容動態創建的彈出窗口,並且我幾乎可以確定我錯過了一些至關重要的東西幫助我解決並充分理解這個問題。用JRadioButtons使用HashMap填充JPanel
我究竟在做什麼?
我有一個程序,通過某些目錄循環,收集所有的文件夾名稱,並將其存儲在ArrayList
。當我嘗試使用該動態創建窗口時出現問題ArrayList
。我不確定如何解決這個問題。
什麼是通過流程
我目前我有3個班。視圖,模型和控制類。包含文件夾的數組存儲在模型類中。我通過控制類檢索它。我在ActionListener
以及HashMap
內創建了一個新的JPanel。我循環通過HashMap
添加String
名稱和JRadioButton
我試圖填充窗口,但我真的不知道如何。
這裏是我的工作的一段代碼:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == theView.viewButton) {
System.out.println("View Button clicked");
theView.setBotTextArea("");
theView.setBotTextArea("Viewing...");
JPanel radioPanel = new JPanel();
// Method that gather folder names and stores it in an array
theModel.listAllFolders();
// Make the categories array and store the names
ArrayList<String> categories = theModel.getListOfCategories();
// Create a hashmap with names and JRadioButtons
HashMap<String, JRadioButton> buttonMap = new HashMap<String, JRadioButton>();
// loop to fill up the HashMap
for (int i = 0; i < categories.size(); i++) {
buttonMap.put(categories.get(i), new JRadioButton(categories.get(i)));
}
for (Entry<String, JRadioButton> entry : buttonMap.entrySet()) {
// Not sure how to retrieve the hashmap data to create and
fill up the window
}
}
我新的極端,以包含HashMap(我努力學習的話),所以我甚至不知道這是否是一個好主意開始。我一直堅持這項任務近3天。在過去,我試圖使用數組來完成類似的任務,但我幾乎可以肯定,這是我的一個巨大的邏輯錯誤,阻止我完成它。
我很感謝在這個問題上的任何新的見解。
爲什麼'ArrayList - > HashMap - > JRadioButton'?爲什麼不是更簡單的'ArrayList - > JRadioButton'?或者,如果你需要創建一個HashMap,那麼爲什麼不用一個for循環來創建JRaidoButton,它填充HashMap,將JRradioButton放到一個ButtonGroup中,並將JRadioButton放到一個JPanel上你將JRadioButtons添加到JPanel?)? –
我的邏輯是我將來可能會在右側'JRadioButton'中分配正確的名稱。 'HashMap'似乎是防止這種情況發生的最佳選擇。儘管如此,我可能會過度複雜化。編輯:你介意在你的編輯中顯示一段代碼嗎?這幾乎是我一直想要做的。 – Lotix
您可能會爲我們過度複雜化它。再次,請給我們更多的細節。我敢肯定,你知道如何將JRadioButtons添加到JPanel,對嗎?只需調用'myPanel.add(myRadioButton)',所以我不確定將您的JRadioButton放到JPanel中有什麼困惑。 –