我有以下布局:

红色,蓝色和绿色部分是JPanel.在红色部分,我有四个JLabel.现在,如果我调整JFrame的大小,标题标签始终位于中心位置.但我更愿意,如果它们在红色部分均匀分布.我应该使用哪种布局?
使用GridLayout(1,0)作为顶级JPanel.这两个数字表示1行和可变数量的列.如果您使用的是JLabel,这就足够了,特别是如果将JLabels对齐常量设置为SwingConstants.CENTER.如果您使用的是填充网格插槽的组件,例如JButtons,那么您可能需要使用GridLayout构造函数的其他变体,例如GridLayout(1,0,?,0).是一个数字告诉GridLayout插槽之间应该有多少水平间隔.
整个GUI当然会使用BorderLayout.
有关此更多更好的信息,请查看课程:在容器中布置组件和布局管理器的可视指南
例如:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
public class LayoutEg {
private static void createAndShowGui() {
String[] labelStrings = {"One", "Two", "Three", "Four"};
JPanel topPanel = new JPanel(new GridLayout(1, 0));
for (String labelString : labelStrings) {
// create labels and center the text
topPanel.add(new JLabel(labelString, SwingConstants.CENTER));
}
topPanel.setBackground(Color.red);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.blue);
// setting preferred size for demonstration purposes only
centerPanel.setPreferredSize(new Dimension(700, 400));
JPanel bottomPanel = new JPanel();
bottomPanel.setBackground(Color.green);
// main panel uses BorderLayout
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.PAGE_START);
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
JFrame frame = new JFrame("LayoutEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2234 次 |
| 最近记录: |