部分取决于您希望如何分配额外的空间。此 GUI 为文本字段和文本区域提供额外的宽度,同时保持按钮居中。文本区域被赋予了额外的高度。
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;
public class BasicLayout {
BasicLayout() {
JPanel gui = new JPanel(new BorderLayout(2,2));
gui.add(new JTextField(), BorderLayout.PAGE_START);
gui.add(new JTextArea(3,15));
JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
controls.add(new JButton("Button1"));
controls.add(new JButton("Button2"));
gui.add(controls, BorderLayout.PAGE_END);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new BasicLayout();
}
});
}
}
更新
一开始我以为你说的是JTextArea
中间部分,后来我仔细看了看。AJTextPane
的大小有点棘手,因为它不接受构造函数中的大小提示。为此,我们可以为其调整容器的首选大小(在本例中为JScrollPane
.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.*;
public class BasicLayout {
BasicLayout() {
JPanel gui = new JPanel(new BorderLayout(2,2));
gui.add(new JTextField(), BorderLayout.PAGE_START);
JTextPane text = new JTextPane();
JScrollPane scroll = new JScrollPane(text);
Dimension d = text.getPreferredSize();
scroll.setPreferredSize(new Dimension(d.width, d.height*3));
gui.add(scroll);
JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
controls.add(new JButton("Button1"));
controls.add(new JButton("Button2"));
gui.add(controls, BorderLayout.PAGE_END);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new BasicLayout();
}
});
}
}