Problems with size of JPanels inside JSplitPane
SSCCE:
Code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
public class SplitPaneDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Dimension dim = new Dimension(500, 300);
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
bluePanel.setMinimumSize(dim);
bluePanel.setPreferredSize(dim);
JPanel yellowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
yellowPanel.setBackground(Color.yellow);
yellowPanel.add(bluePanel);
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
redPanel.setMinimumSize(dim);
redPanel.setPreferredSize(dim);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
yellowPanel, redPanel);
JFrame frame = new JFrame("Split Pane Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(splitPane);
frame.pack();
frame.setVisible(true);
}
});
}
}
Notice how the top panel of the JSplitPane is actually two nested JPanels. When the window containing the JSplitPane is resized, the red panel grows to take up its share of the available space. But the blue panel remains fixed at its preferred size. It also remains fixed when the split divider is dragged. I want it to grow like the red panel.
The problem seems to be that the yellow panel is allocating all the available space to itself instead of resizing its child.
I think I can change this behavior by replacing the yellow panel's LayoutManager. But I don't know which one to use. I hope I don't have to write a custom one.
Any suggestions?
Re: Problems with size of JPanels inside JSplitPane
Quote:
The problem seems to be that the yellow panel is allocating all the available space to itself instead of resizing its child.
FlowLayout shows a component at its preferredSize. If you want the bluePanel to always fill the yellowPanel you can use a BorderLayout and add it at CENTER. Or if you want to be fancy, a GridBagLayout with non-zero weightx/weighty. Or a GridLayout (1, 1) or (1, 0) or (0, 1) or (). Or...
Have you gone through the Lesson: Laying Out Components Within a Container (The Java™ Tutorials > Creating a GUI With JFC/Swing) ?
db
Re: Problems with size of JPanels inside JSplitPane
BorderLayout did the trick, thanks.