java布局不能完全填充_Java Swing gridbaglayout无法填充完整框架

我正在尝试构建类似于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参数,但仍然无法正常工作.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值