gpt4 book ai didi

java - 布局管理器 preferredSize Java

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:12 24 4
gpt4 key购买 nike

我仍在努力学习布局管理器的工作原理。我用两个 JPanel 制作了一个框架。第一个包含带有 boxLayout 的 textArea。第二个包含带有按钮的流布局。

我相应地设置了每个面板的 preferredSize,将它们打包,但得到了意想不到的结果。

import java.awt.*;
import javax.swing.*;

public class LayoutMgrTest
{
public static void main(String[] args)
{
TableBasic frame = new TableBasic();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setVisible(true);


frame.getContentPane().setLayout(new GridLayout(2,1));

JPanel controlPane = new JPanel();
JPanel buttonPane = new JPanel();

controlPane.setLayout(new BoxLayout(controlPane, BoxLayout.PAGE_AXIS));
controlPane.setPreferredSize(new Dimension(200, 200));
controlPane.add(new JScrollPane(new JTextArea()));

buttonPane.setLayout(new FlowLayout(FlowLayout.LEFT));
buttonPane.setPreferredSize(new Dimension(100,20));
buttonPane.add(new JButton("Button1"));
buttonPane.add(new JButton("Button2"));

frame.getContentPane().add(controlPane, BorderLayout.NORTH);
frame.getContentPane().add(buttonPane, BorderLayout.SOUTH);
frame.setSize(new Dimension(500,500));
frame.pack();
}
}

无论我做什么,如果我使用网格布局,它似乎总是为每个控件分配一半的可用空间。有人告诉我:

The height of each row is dependent on the height of each component added in each row.

按钮面板的高度是 20。分配给它的远不止这个:

Wasted space

这段代码有什么问题?
我想保持两个 JPanel 完好无损。将文本框和按钮直接添加到框架很容易,但我需要使用 JPanels 来完成(因为我将添加边框和其他东西)。

最佳答案

这是使用 GridLayout 作为布局管理器的结果。将其更改为 BorderLayout:

frame.getContentPane().setLayout(new BorderLayout());

比如这段代码(我在原来的基础上尽量改了一点):

import java.awt.*;
import javax.swing.*;

public class LayoutMgrTest
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
//frame.setVisible(true);
//frame.getContentPane().setLayout(new BorderLayout());

JPanel controlPane = new JPanel();
JPanel buttonPane = new JPanel();

controlPane.setLayout(new BoxLayout(controlPane, BoxLayout.PAGE_AXIS));
controlPane.setPreferredSize(new Dimension(200, 200));
controlPane.add(new JScrollPane(new JTextArea()));

buttonPane.setLayout(new FlowLayout(FlowLayout.LEFT));
buttonPane.setPreferredSize(new Dimension(100,40));
buttonPane.add(new JButton("Button1"));
buttonPane.add(new JButton("Button2"));

frame.add(controlPane, BorderLayout.NORTH);
frame.add(buttonPane, BorderLayout.SOUTH);
//frame.setSize(new Dimension(500,500));
frame.pack();
frame.setVisible(true);
}
}

生成这个框架:

enter image description here

关于java - 布局管理器 preferredSize Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7050972/

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