문제

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();
            }
        });
    }

}

enter image description here

도움이 되었습니까?

해결책 2

Use

splitPane.setResizeWeight(0.5);

Please see the java doc for more information.

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top