How to add scrollbar to panel in java, without borderlayout?

victorio picture victorio · Mar 10, 2011 · Viewed 25k times · Source

Here is my code:

//this is a JPanel, the gray panel behind the A4 paper
public Panel(int w, int h) {  //w=624, h=600
    this.w = w;
    this.h = h;
    ownlayout();
    setLocation(0, 0);
    setSize(w,h);
    setBackground(Color.gray);

    JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL);
    vbar.setLocation(w-30,0);
    Tab tab = new Tab(w-30,842);
    //Tab is a JPanel too, this is the A4 paper
    add(tab);
    add(vbar);
}
private void ownlayout() {
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    /*layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, w, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, h, Short.MAX_VALUE)
    );*/
}

You can see, the Tab panel's height is bigger than gray Panel's height. So I want, to get a scrollbar in the right side of the gray Panel, which can scroll the tab panel (which is on the gray Panel) up and down. But it only shows the tab panel, and there is no scrollbar! I can do this, if I set the layout border, and not the ownlayout(), but I want a free design, not borderlayout. Please help me with some example!

Answer

iluxa picture iluxa · Mar 10, 2011
JScrollPane thePane = new JScrollPane(yourBigComponent);
container.add(thePane);