【发布时间】:2013-12-05 12:31:35
【问题描述】:
我需要根据他们需要的视觉空间百分比来创建框架内容。 例如,面板 1 为 20%,面板 2 为 80%。 这种布局管理什么布局?
【问题讨论】:
标签: java swing layout-manager
我需要根据他们需要的视觉空间百分比来创建框架内容。 例如,面板 1 为 20%,面板 2 为 80%。 这种布局管理什么布局?
【问题讨论】:
标签: java swing layout-manager
GridBagLayout,但成功满足您的要求 80% - 20%import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "80pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 70;
add(panel1, gbc); // add component to the ContentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the ContentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 2;
gbc.weightx = /*gbc.weighty = */ 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc); // add component to the ContentPane
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
@Override
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
MigLayout
【讨论】:
没有 JDK 布局允许您直接执行此操作。 BoxLayout 和 GridBagLayout 允许您这样做。
使用 GridBagLayout,您可以指定一个介于 0 和 1 之间的 weightx/y 值,它告诉布局管理器如何分配额外空间。因此,假设您以 80/20 的比例创建具有首选大小的组件,它们应该能够以相同的比例增长。
在这方面,BoxLayout 更易于使用,因为您无需指定特定的约束,它只需按照首选大小的比例调整大小。
对于旨在允许您将相对大小指定为简单约束的简单布局管理器,您可以查看Relative Layout。
【讨论】: