gpt4 book ai didi

java - 如何平均分割一个JSplitPane?

转载 作者:行者123 更新时间:2023-12-01 13:06:52 24 4
gpt4 key购买 nike

所以我正在使用 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

最佳答案

正如另一个答案中提到的,setResizeWeight 可能是一种解决方案。然而,这......好吧,设置了调整大小权重,从而以可能不希望的方式改变了分割 Pane 的行为。

您实际上可能只想设置分隔线位置。在这种情况下,您可以调用

splitPane.setDividerLocation(0.5);

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

关于java - 如何平均分割一个JSplitPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23197303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com