0

Hello i wanted to know how to add a ScrollBar at the bottom of a JPanel if i use GridLayout in my desktop app, as far as i know GridLayout only accept as parameter quantity of colums, rows and the horizontal and vertical gap. So how can i add a scroll bar and use it to see the information that's in the JPanel?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jonathan Solorzano
  • 6,812
  • 20
  • 70
  • 131

2 Answers2

3

Put the JPanel with GridLayout into a JScrollPane. E.G. as seen with the two column GridLayout that displays the labels added to the nested layout example.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

If you want the JSrollBar to scroll the JPanel with the gridlayout, then put the grid layout into a scrollpane (remember to extend the scrollable interface)

Read this page of the tutorial to learn how to.

IF you want to use the events from the JScrollBar to change the visible area of your panel then put the panel inside another panel with a JScrollbar on the bottom.

This is an example with a green panel and a scrollbar at the bottom

public class Window extends JFrame {

    public Window() {
        setPreferredSize(new Dimension(500, 500));
        setMinimumSize(new Dimension(500, 500));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(100, 100));
        panel.setBackground(Color.GREEN);
        getContentPane().add(panel, BorderLayout.CENTER);

        JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
        scrollBar.setMinimum(0);
        scrollBar.setMaximum(100);
        scrollBar.setBlockIncrement(30);
        scrollBar.addAdjustmentListener(new AdjustmentListener() {
            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                 System.out.println("Adjustment changed");
            }
        });
        getContentPane().add(scrollBar, BorderLayout.SOUTH);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Window();
    }
}
Alejandro Vera
  • 377
  • 2
  • 12