Lucia
Lucia

Reputation: 4767

java: how to make srollable panel with radio button and labels inside?

I got a JScrollPane in which I want to place a list of radio buttons and labels. My problem is the panel doesn't scroll, I suppose it's because i didn't set a viewport, but how can I set it when I have to many components? My code looks something like this:

JScrollPane panel = new JScrollPane();
JRadioButton myRadio;
JLabel myLabel;
for(int i = 0; i<100; i++){
    myRadio = new JRadioButton();
    myLabel = new JLabel("text");
    panel.add(myRadio);
    panel.add(myLabel);
 }

Thanks.

Upvotes: 2

Views: 2119

Answers (1)

akf
akf

Reputation: 39485

It is better to put your buttons and labels in a wrapper JPanel and then drop that into a JScrollPane.

try this:

    JPanel panel = new JPanel(new GridLayout(0,1));
    JRadioButton myRadio;
    for(int i = 0; i<100; i++){
        myRadio = new JRadioButton("text" + i);
        panel.add(myRadio);
     }
    JScrollPane scrollPane = new JScrollPane(panel);

be sure to look into ButtonGroup as well. ButtonGroups allow you to enforce the single selection constraint common to radio buttons.

Upvotes: 4

Related Questions