【问题标题】:A java sidebar with GridBagLayout带有 GridBagLayout 的 java 侧边栏
【发布时间】:2009-12-15 03:54:24
【问题描述】:

我正在尝试为我正在进行的项目绘制侧边栏。我选择使用 GridBagLayout 是因为我对 BoxLayout 的局限性感到沮丧。有人可以帮助解释我做错了什么。我想要的是侧栏包含两个 JPanel。我的代码将它们放在侧边栏的中间而不是顶部。有人可以解释一下我在这里缺少什么。

    JPanel sideBar = new JPanel();
    sideBar.setBounds(0, 0, 180, (int)this.getBounds().getHeight());
    sideBar.setLayout(new GridBagLayout());


    JPanel optionBar = new JPanel();
    optionBar.setBorder(BorderFactory.createTitledBorder("Box1"));
    optionBar.setLayout(new GridBagLayout());


    JPanel buttonBar = new JPanel();
    buttonBar.setBorder(BorderFactory.createTitledBorder("Options"));
    buttonBar.setLayout(new GridBagLayout());


    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.ipady = 5;
    c.insets = new Insets(10,0,0,0);


    JButton simplify;
    simplify = new JButton("Open");
    simplify.addActionListener( this.listener );
    c.gridy = 0;
    buttonBar.add(simplify, c);

    JButton mergeButton;
    mergeButton = new JButton("Close");
    mergeButton.addActionListener( this.listener );
    c.gridy = 1;
    buttonBar.add(mergeButton, c);

    JButton splitButton;
    splitButton = new JButton("Merge");
    splitButton.addActionListener( this.listener );
    c.gridy = 2;
    buttonBar.add(splitButton, c);

    c.insets = new Insets(0,5,5,5);
    c.gridy = 0;
    sideBar.add(optionBar, c);

    c.gridy = 1;
    c.ipadx = 70;
    sideBar.add(buttonBar, c);

    return(sideBar);

【问题讨论】:

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


    【解决方案1】:

    GridBagLayout 只会分配组件所需的足够垂直空间,其余部分留空。我希望您看到侧栏组件垂直居中?

    为了将组件“推出”,您需要设置垂直权重。如果您在最后一个组件上将weighty 约束设置为 1.0,它将占用该组件的所有剩余垂直空间并将其余部分推到顶部。 (您可能还需要将最后一个面板锚定到 GridBagConstraints.NORTH)。

    sideBar.add(buttonBar, c); 之前尝试c.weighty = 1.0

    【讨论】:

      【解决方案2】:

      如果您熟悉/更熟悉 HTML,可以使用table2gridbag。它是一个小型控制台工具,它采用布局描述(HTML 表格)并将其转换为等效的布局描述以配置 GridBagLayout 管理器

      【讨论】:

        【解决方案3】:

        我的代码放置了它们 在侧边栏的一半而不是在 顶部。

        您需要先阅读Swing tutorial 以了解如何正确使用布局管理器。 BoxLayout 比 GridBagLayout 容易得多,因为您不必学习如何指定约束。但如果您想使用 GridBagLayout,请阅读“如何使用 GridBagLayout”部分。您可能希望专注于处理“weightx 和 weighty”约束的部分。根据我有限的知识,应该有助于解决问题。

        此外,在使用布局管理器时,您不使用 setBounds() 或 setSize()。

        【讨论】:

          猜你喜欢
          • 2016-10-06
          • 1970-01-01
          • 2021-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-20
          • 1970-01-01
          相关资源
          最近更新 更多