Java: how to make a scrollable panel with radio button and labels inside?

I have a JScrollPane in which I want to place a list of radio buttons and labels. My problem is the pane is not scrolling, I suppose because I have not installed the viewport, but how can I install it when I have a lot of 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.

+2


a source to share


1 answer


Better to put your buttons and labels in a wrapper JPanel

and then drop that in 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 . ButtonGroups allow you to enforce the only selection constraint common to radio buttons.

+4


a source







All Articles