- 使用的
FlowLayout
和BorderLayout
的組合。嵌套佈局以獲得您想要的結果是一個不錯的主意。
- 的
JLabel
和JTextField
會去一個JPanel
與FlowLayout
然後又JPanel
與BorderLayout
將保持前面板的NORTH
位置,JTextArea
與JScrollPane
在CENTER
位置。
JPanel topPanel = new JPanel();
JLabel label = new JLabel("Text Field Label");
JTextField jtf = new JTextField(20);
topPanel.add(label);
topPanel.add(jtf);
JPanel bothPanel = new JPanel(new BorderLayout());
JTextArea jta = new JTextArea(20, 40);
bothPanel.add(topPanel, BorderLayout.NORTH);
bothPanel.add(new JScrollPane(jta));
看一看Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FlowBorderDemo {
public FlowBorderDemo() {
JPanel topPanel = new JPanel();
JLabel label = new JLabel("Text Field Label");
label.setForeground(Color.white);
JTextField jtf = new JTextField(20);
topPanel.add(label);
topPanel.add(jtf);
topPanel.setBackground(Color.black);
JPanel bothPanel = new JPanel(new BorderLayout());
JTextArea jta = new JTextArea(20, 40);
JScrollPane scrollPane = new JScrollPane(jta);
scrollPane.setBorder(BorderFactory.createMatteBorder(3, 0, 0, 0, Color.GRAY));
bothPanel.add(topPanel, BorderLayout.NORTH);
bothPanel.add(scrollPane);
bothPanel.setBorder(BorderFactory.createMatteBorder(3, 8, 3, 8, Color.GRAY));
JLabel copyLabel = new JLabel("<html>©2014 peeskillet</html>");
copyLabel.setBackground(Color.LIGHT_GRAY);
copyLabel.setHorizontalAlignment(JLabel.CENTER);
bothPanel.add(copyLabel, BorderLayout.PAGE_END);
JFrame frame = new JFrame();
frame.add(bothPanel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new FlowBorderDemo();
}
});
}
}
謝謝@peeskillet。我從來沒有考慮過將面板數量增加到佈局管理器。但是,我將如何強制在同一個佈局管理器中封裝組件? – Mushy
@穆什你到底想要什麼_wrap_? –
我想留在'FlowLayout'中,並且在'JLabel'和'JTextField'下面包裝'JScrollPane',而不用額外的面板和佈局管理器。 – Mushy