【问题标题】:How to equally split a JSplitPane?如何平均分割 JSplitPane?
【发布时间】:2014-04-21 12:18:40
【问题描述】:

所以我正在使用 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();
            }
        });
    }

}

【问题讨论】:

    标签: java swing jsplitpane


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      使用

      splitPane.setResizeWeight(0.5);
      

      请参阅java doc 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-15
        • 1970-01-01
        • 2015-09-11
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        • 2015-07-01
        相关资源
        最近更新 更多