Java – jscrollpane to scrolling a panel

appletawtjavaswinguser interface

i have to writing an applet, in left side i must use an panel to contain a list of vehicles that can be a list of buttons,what is the problem, number of the vehicles are not given !!!
so, i need to scrolling panel when number of vehicles is too much,

i do this for jframe, but it didn't work correct with panel, please help me with an example

the code i use to scrolling panel is :

 public class VehicleList extends JPanel {
    private ArrayList<VehicleReport> vehicles;
    private ArrayList<JButton> v_buttons =  new ArrayList<JButton>();



 public void showList(ArrayList<Vehicles> vehicles)
 {
   this.vehicles = vehicles;
   //...
    add(getScrollpane());
    setSize(155,300);

 }

public JScrollPane getScrollpane()
{
  JPanel panel = new JPanel();
  panel.setPreferredSize(new DimensionUIResource(150, 300));
   GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints constraint = new GridBagConstraints();
    panel.setLayout(gridbag);
    constraint.fill = GridBagConstraints.HORIZONTAL;
    JLabel title = new JLabel("Vehiles list");
    constraint.gridwidth = 2;
    constraint.gridx = 0;
    constraint.gridy = 0;
    constraint.ipady = 230;
    gridbag.setConstraints(title, constraint);
    panel.add(title);
    // end of set title
    constraint.gridwidth = 1;
    int i=1;

    for(JButton jb : v_buttons )
    {
        constraint.gridx =0;
        constraint.gridy = i;
        gridbag.setConstraints(jb, constraint);
        panel.add(jb);
        JLabel vehicle_lable = new JLabel("car" + i);
        constraint.gridx = 1;
        constraint.gridy = i;
        gridbag.setConstraints(vehicle_lable, constraint);
        panel.add(vehicle_lable);
        i++;
    }
JScrollPane jsp = new JScrollPane(panel);
 return jsp;

}

}

in jaframe after add jscrollpane to jframe i place this

pack();

setSize(250, 250);

setLocation(100, 300);

and it work clearly!!!!

Best Answer

You also don't show us the layout manager of the VehicleList JPanel. In case you aren't setting it, it defaults to FlowLayout, unlike JFrame (which you mentioned this does work in), whose content pane defaults to BorderLayout. So maybe you just need to change the relevant code from:

//...
add(getScrollpane());

to

//...
setLayout(new BorderLayout());
add(getScrollpane(), BorderLayout.CENTER);
Related Topic