Use
splitPane.setResizeWeight(0.5);
Please see the java doc for more information.
Domanda
So i am using Java and Swing and am trying to program a window with a JSplitPane
equally split on each side. I have got the JSplitPane
, however one side is nearly the full size of the window and the other is tiny.
package com.harrykitchener.backup;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Main
{
private JMenuBar menuBar;
private JMenu fileMenu, editMenu, helpMenu;
private JPanel leftPanel, rightPanel;
private JButton openButton;
public Main()
{
JPanel mainCard = new JPanel(new BorderLayout(8, 8));
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
editMenu = new JMenu("Edit");
helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
mainCard.add(menuBar);
leftPanel = new JPanel();
rightPanel = new JPanel();
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
JFrame window = new JFrame("Pseudo code text editor");
window.setJMenuBar(menuBar);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(splitPane);
window.setSize(1280, 720);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Main();
}
});
}
}
Soluzione 2
Altri suggerimenti
As mentioned in the other answer, setResizeWeight
might be one solution. However, this ... well, sets the resize weight, and thus changes the behavior of the split pane in a way that may not be desired.
It might be that you actually just want to set the divider location. In this case, you could call
splitPane.setDividerLocation(0.5);
However, due to some peculiarities in the split pane implementation, this has to be done after the split pane was made visible. For my application, I created a small utility method, that defers setting the divider location by putting a task to set it on the EDT:
/**
* Set the location of the the given split pane to the given
* value later on the EDT, and validate the split pane
*
* @param splitPane The split pane
* @param location The location
*/
static void setDividerLocation(
final JSplitPane splitPane, final double location)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
splitPane.setDividerLocation(location);
splitPane.validate();
}
});
}
It can then be called as
setDividerLocation(splitPane, 0.5);