So I am programming an application using Java Swing, and I am wondering how to make it so that when the entire application gets resized only certain panels get resized in various ways. Take a look at the two pictures below:
I have three vertical panels as you can see. Now when the application's height is extended all three panels heights should increase also, that works fine. However when the width is increased I want it so that only the middle panel's (which will be the "workspace") width is increased. Instead, as you can see, the last-to-be-added third panel on the right is the only one whose width increases.
How do I go about to make it so that only the middle JPanel
stretches & shrinks as the entire window is resized in the x axis? Also, later I would like to make it so that this workspace panel isn't always going to be in the middle; as the user can move the other two panels around to customize the app to their own taste, such as to make the two other panels stacked up on top of each other to the left while the workspace is on the right. However regardless of where it is I want the workspace panel to be the one the resizes, how do I do that?
The trick is to call setResizeWeight(double)
on the correct split pane with the appropriate value. E.G.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class DualingSplitPanes {
private JComponent ui = null;
DualingSplitPanes() {
initUI();
}
protected final void addPanelsToUi(JPanel p1, JPanel p2, JPanel p3) {
JSplitPane sp1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p1, p2);
JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp1, p3);
sp2.setResizeWeight(1);
ui.add(sp2);
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel treeContainer = new JPanel(new GridLayout());
JTree tree = new JTree();
tree.setVisibleRowCount(5);
for (int i=tree.getVisibleRowCount()-1; i>-1; i--) {
tree.expandRow(i);
}
treeContainer.add(new JScrollPane(tree));
JPanel workSpaceContainer = new JPanel(new GridLayout());
workSpaceContainer.add(new JTextArea(5, 10));
JPanel searchContainer = new JPanel(new BorderLayout(4, 4));
searchContainer.add(new JScrollPane(new JTextArea(5, 10)));
addPanelsToUi(treeContainer, workSpaceContainer, searchContainer);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
DualingSplitPanes o = new DualingSplitPanes();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}