除了GridBaglayout之外,请建议我使用的基本布局

时间:2014-05-03 18:24:42

标签: java swing user-interface layout-manager gridbaglayout

好的我有a panel,我想放置two panels on to itleft and right,这样右侧面板应该是左侧面板宽度的两倍。

我想在左侧面板中添加一个菜单,所选项目的详细信息将显示在右侧面板中。

其次,当窗口扩展时,面板及其组件的大小应按比例增加(如果有任何方法可用于此目的,请建议!)

我确实尝试过使用GridBagLayout,但我认为我还没有把握好。所以请建议最简单的布局管理器,它可以满足我的目的。


编辑: - 我在使用网格包时遇到的问题

//Set Layout
        setLayout(new GridBagLayout());
        GridBagConstraints c= new GridBagConstraints();

        //Set Layout constraints of components and add them to the MainPanel
        c.gridx=0;
        c.gridy=0;
        c.weightx=0.5;
        c.insets= new Insets(5,5,5,5);
        c.fill=GridBagConstraints.BOTH;
        add(iListPanel);
        iListPanel.setBorder(BorderFactory.createTitledBorder("Check") );

        GridBagConstraints c1= new GridBagConstraints();
        c.gridx=1;
        c.gridy=0;
        c.weightx=1;
        c.insets= new Insets(5,5,5,5);
        c.fill=GridBagConstraints.BOTH;
        add(iDetailsPanel);
        iDetailsPanel.setBorder(BorderFactory.createTitledBorder("Check"));

enter image description here

2 个答案:

答案 0 :(得分:1)

在Java附带的布局管理器中,我认为GridBagLayout是最简单的。值得花时间学习它,因为它是关于唯一能够中途胜任的布局管理者。这应该这样做:

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c;

JPanel left = new JPanel();
left.setBorder(BorderFactory.createTitledBorder("Left"));
c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1;
c.fill = c.BOTH;
panel.add(left, c);

JPanel right = new JPanel();
right.setBorder(BorderFactory.createTitledBorder("Right"));
c = new GridBagConstraints();
c.weightx = 2;
c.weighty = 1;
c.fill = c.BOTH;
panel.add(right, c);

但是,从您对问题的描述来看,JSplitPane听起来会为您提供更好的服务。它是一个现成的组件,可以执行或多或少的要求,并且还具有用户可调整大小的分隔符。一个例子:

JSplitPane pane = new JSplitPane();
pane.setResizeWeight(1/3f); // right will be twice size of left

JPanel left = new JPanel();
left.setBorder(BorderFactory.createTitledBorder("Left"));
pane.setLeftComponent(left);

JPanel right = new JPanel();
right.setBorder(BorderFactory.createTitledBorder("Right"));
pane.setRightComponent(right);

编辑:原始代码的问题在于它没有使用约束。

add(iListPanel);

应该是:

add(iListPanel, c);

同样适用于iDetailsPanel

答案 1 :(得分:0)

您想使用BorderLayout。

panel.add(panelLeft,"West");
panel.add(panelRight,"East");

北,南和中心也可用