I’m trying put a JPanel (GridLayout 0, 1) with JButtons it, within the ViewPort of a JScrollPane. This is easy enough to do, but it doesn’t behave “properly” when resizing the parent JFrame. Buttons resize to fill the entire panel as intended, but with one major limitation. If I attempt to resize the frame horizontally (in run-time by corner dragging), it stops after a point. The panel will extend infinitely, but it won’t contract below the minimum size necessary to display the Text on the button with the shortest Text.
Resizing the frame vertically has no such issue. The frame will contract down to nothing. The buttons will squish until they hit their MinimumSize, after which point they simply clip outside the frame. This is the behaviour I want, because I intend to stick the whole thing inside a JScrollPane, at which point a scrollbar would appear. I want the same behaviour horizontally, but I can’t get it no matter what I try.
So far, I’ve tried using GridLayout and GridBagLayout. The latter seems to be needlessly heavy-handed for just a single column of buttons. However, because this is a column, I can’t use FlowLayout as that arranges objects laterally and I don’t know how to change it. More to the point – both GridLayout and GridBagLayout full space and justify buttons in a way that I like, which I haven’t been able to accomplish with other layout managers.
I threw together a really ugly test example to demonstrate the behaviour I see. It’s not meant to be pretty or extensible as I’m just learning the mechanics of it.
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocation(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel(new GridLayout(0, 1));
panel1.setMinimumSize(new Dimension(10,10));
panel1.setBackground(Color.BLUE);
JTabbedPane tabbedPane = new JTabbedPane();
JScrollPane scrollPane = new JScrollPane(panel1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tabbedPane.addTab("Tab ", scrollPane);
JButton button1 = new JButton("Button 1");
button1.setPreferredSize(new Dimension(300,100));
panel1.add(button1);
JButton button2 = new JButton("Button 2---------------");
button2.setPreferredSize(new Dimension(300,100));
panel1.add(button2);
JButton button3 = new JButton("Button 3");
button3.setPreferredSize(new Dimension(300,100));
panel1.add(button3);
JButton button4 = new JButton("But");
button4.setPreferredSize(new Dimension(300,100));
panel1.add(button4);
frame.add(tabbedPane);
frame.setVisible(true);
George Minkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.