gpt4 book ai didi

java - 使用 BorderLayout 创建两个偶数列

转载 作者:行者123 更新时间:2023-11-29 05:15:54 25 4
gpt4 key购买 nike

我正在尝试使用 BorderLayout() 创建一个程序,我希望它看起来像这样(但具有均匀的左右高度等)

enter image description here

尽管我在调整两个 JPanel(大框内的两个框)的大小时遇到​​了问题。目前我的 GUI 看起来像这样,

enter image description here

我相信这是由于 CENTER 仍然存在,我查看了如何删除它但无法让它工作,

问题

我可以编辑它使其看起来像顶部图像吗。

package fuelstation;
import java.awt.*;
import java.util.*;
import javax.swing.*;


public class Fuelstation extends JFrame {


JButton btn1 = new JButton("Random Button");


public Fuelstation() {
JFrame frame = new JFrame("Fuel Station");
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.setPreferredSize(new Dimension(500,350));
frame.setMaximumSize(new Dimension(500,350));

// Left Hand Side
JPanel lhs = new JPanel();
JTextArea tf_list = new JTextArea();
tf_list.setEditable(false);
tf_list.setWrapStyleWord(true);
tf_list.setText("This is a list of items");
lhs.add(tf_list);
tf_list.setSize(245, 325);
lhs.setBorder(BorderFactory.createTitledBorder("Left"));
// Left Hand Side End


// Right Hand Side
JPanel rhs = new JPanel();
rhs.setAlignmentX(Component.CENTER_ALIGNMENT);
rhs.setBorder(BorderFactory.createTitledBorder("Right"));
rhs.add(btn1);
tf_list.setSize(245, 325);

JPanel center = new JPanel();
center.setSize(0, 0);
// Right Hand Side End

frame.add(lhs, BorderLayout.WEST);
frame.add(center, BorderLayout.CENTER);
frame.add(rhs, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

}

public static void main(String[] args) {
Fuelstation gui = new Fuelstation();
}

}

最佳答案

您需要放弃使用 BorderLayout 的要求。使用 BorderLayout 时组件的大小调整策略在 class javadoc 中说明。

The components are laid out according to their preferred sizes and the constraints of the container's size. The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over.

通过强制您的 JFrame 达到特定大小

frame.setResizable(false);
frame.setPreferredSize(new Dimension(500,350));
frame.setMaximumSize(new Dimension(500,350));

您的中心组件将占用额外的宽度,因为 EASTWEST 组件只会垂直拉伸(stretch)。

所以你需要使用另一个LayoutManager。您可以使用 Visual guide to layout managers了解可用的 LayoutManager 及其功能。该文档指出 GridLayout 是一个不错的选择:

GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns

关于java - 使用 BorderLayout 创建两个偶数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26553164/

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