ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java Swing gridbaglayout无法填充完整框架

2019-11-09 05:03:14  阅读:259  来源: 互联网

标签:gridbaglayout swing layout-manager java


我正在尝试构建类似于JProgressBar的组件,该组件将显示三个状态而不是两个状态,如here所示.

我通过将三个JLabel组件(具有三种不同的背景颜色)添加到具有设置为GridBagLayout的面板中来构建此组件.我已经为这些标签分配了相应的权重,以便根据父面板的大小调整它们的大小.下面是相应的示例代码:

public class CustomProgressBar {

  public static void main(String[] args) {

    JFrame frame = new JFrame("test");

    JPanel panel = new JPanel();

    double firstLabelWeight = 0.10d;
    double secondLabelWeight = 0.20d;
    double thirdLabelWeight = 1d - firstLabelWeight - secondLabelWeight;

    JLabel firstLabel = new JLabel();
    firstLabel.setOpaque(true);
    firstLabel.setBackground(Color.GREEN);

    JLabel secondLabel = new JLabel();
    secondLabel.setOpaque(true);
    secondLabel.setBackground(Color.YELLOW);

    JLabel thirdLabel = new JLabel();
    thirdLabel.setOpaque(true);
    thirdLabel.setBackground(Color.RED);

    panel.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;

    gbc.weightx = firstLabelWeight;
    gbc.weighty = 1d;
    panel.add(firstLabel, gbc);

    gbc.weightx = secondLabelWeight;
    gbc.weighty = 1d;
    panel.add(secondLabel, gbc);

    gbc.weightx = thirdLabelWeight;
    gbc.weighty = 1d;
    panel.add(thirdLabel, gbc);

    panel.setBackground(Color.BLACK);
    panel.setPreferredSize(new Dimension(157, 50));

    frame.add(panel);
    frame.setVisible(true);
    frame.pack();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}

现在这种方法的问题在于,当我尝试调整JFrame的大小时,上面的三个标签没有填充父面板中的整个水平空间,并且在面板的末端看到了黑色条纹,如here所示.

我也尝试设置gbc.fill和gbc.anchor参数,但仍然无法正常工作.

对此问题的任何帮助将不胜感激!谢谢 :)

解决方法:

为了克服舍入问题,您可以通过以下方式覆盖面板的布局:

class MyLayout extends GridBagLayout
{
  private Component owner;

  public MyLayout(Component owner)
  {
    this.owner = owner;
  }

  @Override
  protected void adjustForGravity(GridBagConstraints constraints,
                                  Rectangle          rect)
  {
    // Adjust position and width of first (GREEN) label if necessary
    if ((rect.x > 0) && (rect.x <= 2))
    {
      rect.width += rect.x;
      rect.x = 0;
    }

    // Adjust width of last (RED) label if necessary
    int gap = owner.getWidth() - rect.x - rect.width;
    if ((gap > 0) && (gap <= 2))
      rect.width += gap;
  }

} // class MyLayout

然后,当然可以通过以下方式设置面板的布局:

panel.selLayout(new MyLayout(panel));

标签:gridbaglayout,swing,layout-manager,java
来源: https://codeday.me/bug/20191109/2011894.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有