Reputation: 65
I have created a JPanel
inside which there is a JScrollPane
. I want to display only 3 items there and exceeding these, I can scroll down to view them.
I have used the code below to create the JPanel
and the JScrollPane
JScrollPane slide_scroll = new JScrollPane();
slide_scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
slide_scroll.setBounds(1158, 11, 196, 528);
contentPane.add(slide_scroll);
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new GridLayout(5,1));
slide_scroll.setViewportView(scrollPanel);
But after adding a 6th item, all the items are displayed in a tabular way instead of a single column. I want that, when the 6th one is added, I use the scroll bar to be able to view it
Upvotes: 1
Views: 199
Reputation: 44414
From the documentation for GridLayout:
When both the number of rows and the number of columns have been set to non-zero values, either by a constructor or by the setRows and setColumns methods, the number of columns specified is ignored. Instead, the number of columns is determined from the specified number of rows and the total number of components in the layout. So, for example, if three rows and two columns have been specified and nine components are added to the layout, they will be displayed as three rows of three columns. Specifying the number of columns affects the layout only when the number of rows is set to zero.
Your layout will always have five rows. The fact that you specified one column is irrelevant.
If you want your layout to always have one column, use new GridLayout(0, 1)
.
Upvotes: 4