如何平分JSplitPane?

时间:2014-04-21 12:18:40

标签: java swing jsplitpane

所以我正在使用Java和Swing,我正在尝试编写一个窗口,每边都有JSplitPane等分。我有JSplitPane,但是一边几乎是窗户的全尺寸,另一边很小。

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 个答案:

答案 0 :(得分:1)

如其他答案所述,setResizeWeight可能是一种解决方案。但是,这...... 设置调整大小权重,从而以可能不需要的方式更改拆分窗格的行为。

可能您实际上只是想设置分隔符位置。在这种情况下,您可以致电

splitPane.setDividerLocation(0.5);

但是,由于拆分窗格实现中的某些特性,必须在分割窗格可见后完成此操作。对于我的应用程序,我创建了一个小实用程序方法,通过在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();
        }
    });
}

然后可以将其称为

setDividerLocation(splitPane, 0.5);

答案 1 :(得分:0)

使用

splitPane.setResizeWeight(0.5);

有关详细信息,请参阅java doc