我正在尝试构建一个类似于JProgressBar的组件,它可以显示三种状态,而不是像这里展示的两种状态。
我通过向一个布局设置为GridBagLayout的面板添加三个JLabel组件(具有三种不同的背景颜色)来构建此组件。我已经分配了对应的权重给这些标签,以便它们根据父面板的大小进行调整大小。下面是相应的示例代码:
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的大小时,上述三个标签未填满父面板中的完整水平空间,我们会看到如此处所示的黑色条纹。
我已经尝试设置gbc.fill和gbc.anchor参数,但仍然不起作用。
非常感谢您提供有关此问题的任何帮助!谢谢 :)