我有以下布局:
红色、蓝色和绿色部分是JPanel。在红色部分,我有四个 JLabel。现在,如果我调整 JFrame 的大小,标题标签将始终位于中心。但我更希望它们在红色部分水平均匀分布。我应该使用哪种布局?
最佳答案
为顶部的 JPanel 使用 GridLayout(1, 0)。这两个数字表示 1 行和可变数量的列。如果您正在使用 JLabels,这就足够了,尤其是当您将 JLabels 对齐常量设置为 SwingConstants.CENTER 时。如果您正在使用填充网格槽的组件,例如 JButtons,那么您可能需要使用 GridLayout 构造函数的其他变体,例如 GridLayout(1, 0, ?, 0) 其中 ?是一个数字,它告诉 GridLayout 插槽之间应该有多少水平间隔。
整个 GUI 当然会使用 BorderLayout。
有关这方面的更多更好的信息,请查看 Lesson: Laying Out Components Within a Container和 A Visual Guide to Layout Managers
例如:
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();
}
});
}
}
关于java - 如何用Java swing做这个布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8465428/