[英]Adding components via code
我試圖動態地繪制到一個JPanel(位於ScrollPane中),一堆標簽和RadioButtons。 我收到一個帶有“ Advice”對象的ArrayList,我想遍歷它們以用一種具有描述它們的標簽的方式來表示它們,然后是兩個單選按鈕(選擇“是”或“否”)。
但是目前,在JFrame的構造函數中使用以下代碼,它無法正常工作:
// My constructor
public CoachingFrame(AdvicesManager am) {
initComponents();
this.am = am;
// I set the layout for the inner panel (since ScrollPane doesn't allow BoxLayout)
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Iterate over the arraylist
for(int i=0;i<am.advices.size();i++){
//Add elements to the panel
panel.add(new JLabel( am.advices.get(i).getQuestion()));
ButtonGroup group = new ButtonGroup();
// Group the RadioButtons inside another panel, so I can use FlowLayout
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout());
JRadioButton rad1 = new JRadioButton();
JRadioButton rad2 = new JRadioButton();
group.add(rad1);
group.add(rad2);
buttonsPanel.add(rad1);
buttonsPanel.add(rad2);
// Add the radiobuttons' panel to the main one, and revalidate
panel.add(buttonsPanel);
panel.revalidate();
}
// Finally, add the panel to the ScrollPane.
questions.add(panel);
}
我正確地收到了arraylist; 我已經檢查過了。 問題似乎出在噴塗組件時。
由於我一直使用NetBeans GUI創建器,因此我不太習慣通過代碼添加組件。 有人能幫我嗎? 我想我在這里錯過了一些東西。
編輯:請注意,“問題”是ScrollPane對象!
編輯2:此“問題”面板應繪制所有這些組件: http : //i.imgur.com/tXxROfn.png
正如Kiheru所說,ScrollPane不允許使用.add()添加視圖(例如JPanel),而是必須使用.setViewportView(Component)。 現在工作正常,謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.