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?
Asked
Active
Viewed 936 times
0

mKorbel
- 109,525
- 20
- 134
- 319

Jonathan Solorzano
- 6,812
- 20
- 70
- 131
-
Use a different layout manager or a compound layout, something like `BorderLayout` or `GridBagLayout` should do the trick – MadProgrammer Jul 09 '14 at 04:36
-
if i use GridBag Layout how would i do that? – Jonathan Solorzano Jul 09 '14 at 04:38
-
Use `JScrollPane` then – Mukesh Soni Jul 09 '14 at 04:39
-
Welcome to Stack Overflow! Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem, this will reduce the guess work and produce better response – MadProgrammer Jul 09 '14 at 04:39
2 Answers
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
-
if you go for the JScrollPane solution, remembar that you can hide the vertical scrollbar using the scroll policies. Read the documentation for that. – Alejandro Vera Jul 09 '14 at 12:39
-