[英]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.