I have a JFrame with BorderLayout and I have a JTextPane/JScrollPane at NORTH a splitpane in the CENTER and a JPanel with 4 JButtons on it at SOUTH. My Frame's size is (500, 470). I want the JTextPane to fill most of the window so I set its preferredSize to (500, 450) but it has no effect.
Here is a picture about what happens: http://postimg.org/image/3wslmppx7/
and here is my code:
public void initGUI()
{
configWindow = new JFrame();
configWindow.setTitle(node.getDispName()+ " [" + node.getIp() + "] configuration");
configWindow.setSize(500, 470);
configWindow.setLocation(TopologyMain.dim.width/2-configWindow.getSize().width/2, TopologyMain.dim.height/2-configWindow.getSize().height/2);
configWindow.getContentPane().setLayout(new BorderLayout());
configPane = new JTextPane();
configPane.setEditable(true);
configPane.setName("Config");
configPane.setPreferredSize(new Dimension(500, 450));
configPane.setBackground(Color.black);
configPane.setCursor(new Cursor(Cursor.TEXT_CURSOR));
scrollPane = new JScrollPane(configPane);
scrollPane.setPreferredSize(new Dimension(500, 450));
configWindow.getContentPane().add(scrollPane, BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
//buttonPanel.setPreferredSize(new Dimension(500, 20));
GBC.insets = new Insets(5,5,5,5);
read = new JButton("Read");
GBC.gridx = 0;
GBC.gridy = 1;
GBC.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(read, GBC);
apply = new JButton("Apply");
GBC.gridx = 1;
GBC.gridy = 1;
GBC.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(apply, GBC);
load = new JButton("Load");
GBC.gridx = 2;
GBC.gridy = 1;
GBC.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(load, GBC);
save = new JButton("Save");
save.setEnabled(false);
GBC.gridx = 3;
GBC.gridy = 1;
GBC.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(save, GBC);
configWindow.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scrollPane, buttonPanel);
splitPane.setEnabled(true);
configWindow.getContentPane().add(splitPane, BorderLayout.CENTER);
configWindow.setVisible(true);
fileChooser = new JFileChooser();
}
Solution from Gabriel Negut in the comments:
Use pack()
- but only call it after you have added everything to the window.
From the documentation:
public void pack()
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.
If the window and/or its owner are not displayable yet, both of them are made displayable before calculating the preferred size. The Window is validated after its size is being calculated.