【发布时间】:2016-01-03 18:19:01
【问题描述】:
我正在尝试动态地绘制成 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);
}
我正确收到了数组列表;我已经检查过了。问题似乎出在绘制组件时。
由于我一直使用 NetBeans GUI 创建器,我不太习惯通过代码添加组件。有人能帮我吗?我想我在这里遗漏了一些东西。
编辑:注意“问题”是 ScrollPane 对象!
编辑 2:这个“问题”面板应该绘制所有这些组件:http://i.imgur.com/tXxROfn.png
【问题讨论】:
-
在您的面板上尝试
pack()方法 -
尝试通过minimal reproducible example 向我们展示您的最佳尝试(请查看链接)。还张贴您所看到的和您正在努力实现的目标的图像。这将有助于我们更好地了解您的问题。
-
我觉得现在调试起来更直观更容易了
-
"请注意,"questions" 是 ScrollPane 对象!"。这可能就是问题所在。内容不会像在其他组件中那样添加到 JScrollPane。使用JscrollPane.setViewportView(Component) 代替
.add()设置视图。