我需要根据他们所需的视觉空间百分比来创建框架内容。 例如,面板20%,面板2面板180%。 这种布局管理有什么布局?
答案 0 :(得分:11)
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
答案 1 :(得分:3)
所有JDK布局都不允许您直接执行此操作。 BoxLayout和GridBagLayout排序允许你这样做。
使用GridBagLayout,您可以指定0到1之间的weightx / y值,它告诉布局管理器如何分配额外的空间。因此,假设您创建的组件的首选大小为80/20,那么它们应该能够以相同的比例增长。
BoxLayout在这方面更容易使用,因为您不需要指定一个特定的约束,它只是按照首选大小的比例调整大小。
对于一个旨在允许您将相对大小指定为简单约束的简单布局管理器,您可以查看Relative Layout。