问题描述
我如何将 b6 放在顶部中心 和 b4 在底部中心 以及如何更改拆分面板位置
解决方法
- 在拆分窗格的左侧,将组合框置于
GridBagLayout
(无限制)中,使其水平和垂直居中。 - 拆分窗格的右侧。
GridLayout
带有垂直填充。添加EmptyBorder
以获取组件周围的填充。 - 将拆分窗格放在
CENTER
的BorderLayout
中 -
Traducteur
标签位于边框布局的PAGE_START
中。 - 带有
Help
的面板中的Exit
/FlowLayout
按钮。将该面板放在边框布局的PAGE_END
中。
/鳍
这可能是这样的:
,首先看一下Laying Out Components Within a Container
您需要分解您的需求,并专注于哪些布局能够满足您的需求。
我会从 BorderLayout
开始,因为它使您能够在顶部和底部有两个组件,它们遵循这些组件的首选大小,并且可以允许中心组件根据窗口的可用空间。
标题很简单,因为它只是一个 JLabel
。对于按钮,我使用了 JPanel
和 GridBagLayout
,因为默认情况下它会将组件居中,但不会均匀地填充它们,因此请注意这一点。
JSplitPane
的前导和尾随组件我都使用了 GridBagLayout
,因为它允许将子组件布置在容器的中心,并在以下方面提供了很大的灵活性如何管理组件。
我使用了 EmptyBorder
在组件的某些部分周围添加了一些填充。有多种方法可以实现这一点,但这只是一种方法。
请注意,GridBagLayout
非常灵活,但它是一个复杂的布局管理器。
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JLabel label = new JLabel("Traducteur");
label.setHorizontalAlignment(JLabel.CENTER);
label.setBorder(new EmptyBorder(10,10,10));
add(label,BorderLayout.NORTH);
JPanel actions = new JPanel(new GridBagLayout());
actions.add(new JButton("Help"));
actions.add(new JButton("Exit"));
actions.setBorder(new EmptyBorder(10,10));
add(actions,BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane();
JPanel leadingPane = new JPanel(new GridBagLayout());
leadingPane.setBorder(new EmptyBorder(40,20,40,20));
JComboBox<String> comboBox = new JComboBox<>();
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement("In English");
comboBox.setModel(model);
leadingPane.add(comboBox);
splitPane.setLeftComponent(leadingPane);
JPanel trailingPane = new JPanel(new GridBagLayout());
trailingPane.setBorder(new EmptyBorder(40,20));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
trailingPane.add(new JTextField("Some text"),gbc);
trailingPane.add(new JTextField("Some more text"),gbc);
splitPane.setRightComponent(trailingPane);
add(splitPane);
}
}
}