BorderLayout 没有为此任务剪切,因为它为 CENTER 组件提供了所有剩余空间 . 如果您可以将布局更改为 GridBagLayout ,则最简单的方法是将最左侧的组件全部留在空间上 .
示例:
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
frame.add(new JTextArea("Hello World!"), gbc);
gbc.weightx = 0;
frame.add(new JButton("Copy"), gbc);
frame.add(new JButton("Paste"), gbc);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
如果你真的想使用 BorderLayout ,你可以将按钮组合在一起并将它们添加到东方,将文本字段添加到中心,执行以下操作:
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.add(new JTextArea("Hello World!"), BorderLayout.CENTER);
frame.add(new JPanel(new GridLayout(1, 0)) {{
add(new JButton("Copy"));
add(new JButton("Paste"));
}}, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}