我还在努力学习布局管理器的工作方式.我用两个JPanel制作了一个Frame.第一个包含带有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();
}
}
Run Code Online (Sandbox Code Playgroud)
无论我做什么,如果我使用网格布局,它似乎总是为每个控件分配一半的可用空间.有人告诉我:
每行的高度取决于每行中添加的每个组件的高度.
buttonpane的高度为20.它的分配远远超过它:

这段代码出了什么问题?
我想请保留两张JPanels.简单地将文本框和按钮直接添加到框架很容易,但我需要使用JPanels(因为我将添加边框和其他东西).
这是使用GridLayout作为布局管理器的结果.将其更改为BorderLayout:
frame.getContentPane().setLayout(new BorderLayout());
Run Code Online (Sandbox Code Playgroud)
例如,这段代码(我从原版中改变了一点):
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);
}
}
Run Code Online (Sandbox Code Playgroud)
生成此框架:

我相应地设置了每个面板的preferredSize,
那是另一个问题.您不应该设置首选大小.这是布局管理器的工作.只需将组件添加到面板中,然后让布局管理器完成其工作.
大多数组件都有默认的首选大小.对于一些人,你需要给它一点提示.例如,当使用文本区域时,您将通过使用以下方式给出"建议的"首选大小:
JTextArea textArea = new JTextArea(rows, columns);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15302 次 |
| 最近记录: |