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

25,070
JScrollPane thePane = new JScrollPane(yourBigComponent);
container.add(thePane);
Share:
25,070
victorio
Author by

victorio

Updated on December 28, 2020

Comments

  • victorio
    victorio over 3 years

    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!

  • Goaler444
    Goaler444 about 11 years
    the container is the place holder for your big component with the scroll pane