[英]Adding components via code
I'm trying to have painted into a JPanel (which is inside a ScrollPane), a bunch of labels and RadioButtons, dynamically. 我试图动态地绘制到一个JPanel(位于ScrollPane中),一堆标签和RadioButtons。 I receive an ArrayList with "Advice" objects, and I want to iterate over them to represent them in a way I have a label that describes them, and then, two radio buttons (to choose "Yes" or "No"). 我收到一个带有“ Advice”对象的ArrayList,我想遍历它们以用一种具有描述它们的标签的方式来表示它们,然后是两个单选按钮(选择“是”或“否”)。
But at the moment, with this code at the JFrame's constructor, it's not properly working: 但是目前,在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);
}
I receive the arraylist correctly; 我正确地收到了arraylist; I already checked that. 我已经检查过了。 The problem seems to be when painting the components. 问题似乎出在喷涂组件时。
Since I always use the NetBeans GUI creator, I'm not very used to add components via code. 由于我一直使用NetBeans GUI创建器,因此我不太习惯通过代码添加组件。 Can someone help me? 有人能帮我吗? I guess I'm missing something here. 我想我在这里错过了一些东西。
edit: Note that "questions" is the ScrollPane object! 编辑:请注意,“问题”是ScrollPane对象!
edit 2: This "questions" panel should have all those components painted: http://i.imgur.com/tXxROfn.png 编辑2:此“问题”面板应绘制所有这些组件: http : //i.imgur.com/tXxROfn.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.