我有JPanel
默认使用FlowLayout
经理。我喜欢文档样式FlowLayout
的优点,我在其中使用自动换行添加一个组件,但希望组件强制选择新行。
我读过如果我使用BoxLayout
我可以插入一种component return key
并强制组件在新行上开始。我需要有关我的决定的指导,哪种方法更好。
我在一行上有一个JLabel
和JTextField
,并希望将JTextArea
包裹在JScrollPane
下面。
答案 0 :(得分:2)
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));
1}}位置。
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();
}
});
}
}
查看Laying Out Components Within a Container
{{1}}