简体   繁体   中英

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. 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").

But at the moment, with this code at the JFrame's constructor, it's not properly working:

// 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; 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. Can someone help me? I guess I'm missing something here.

edit: Note that "questions" is the ScrollPane object!

edit 2: This "questions" panel should have all those components painted: http://i.imgur.com/tXxROfn.png

As Kiheru said, ScrollPane doesn't allow views (like my JPanel) to be added with .add(), instead, I had to use .setViewportView(Component). Now it's working perfectly, thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM