GridBagConstraints无法正常工作?需要从面板的最左侧开始

时间:2014-01-17 00:52:28

标签: java swing gridbaglayout

我正在设置一个面板,我正在使用GridBagLayout。但是,当我设置面板时,标签不是按照我想要的方式排列(我希望它们像一个统计表一样阅读)rotationLabels应该显示在最左边,但它们显示在中间。我在代码中遗漏了什么吗?

GridBagConstraints rotationGB = new GridBagConstraints();
            rotationGB.insets = new Insets(5,5,5,5);
            rotationGB.anchor = GridBagConstraints.LINE_START;
            rotationPanel = new JPanel(new GridBagLayout());
            rotationLabels = new JLabel[countStarters(team)];
            eraArray = new JLabel[countStarters(team)];
            winArray = new JLabel[countStarters(team)];
            lossArray = new JLabel[countStarters(team)];
            savesArray = new JLabel[countStarters(team)];
            bsArray = new JLabel[countStarters(team)];
            resetXY(0,0);
            for(int i = 0; i < countStarters(team); i++){
                labelX = 0;
                final int n = i;
                rotationLabels[i] = new JLabel(team.rotation.get(i).getName());
                    //Label setup code
                //Mouse listener stuff

                addGCComp(rotationLabels[i], rotationPanel, rotationGB, labelX, labelY, labelSize);
                labelX += 125;
                eraArray[i] = new JLabel(pitcherF.format(team.rotation.get(i).getERA()));
                eraArray[i].setForeground(Color.BLACK);
                addGCComp(eraArray[i], rotationPanel, rotationGB, labelX, labelY, labelSize);
                labelX += 75;
                DecimalFormat df = new DecimalFormat("0");
                winArray[i] = new JLabel(df.format(team.rotation.get(i).getPitcherWins()));
                winArray[i].setForeground(Color.BLACK);
                addGCComp(winArray[i], rotationPanel, rotationGB, labelX, labelY, labelSize);
                labelX += 75;
                lossArray[i] = new JLabel(df.format(team.rotation.get(i).getPitcherLosses()));
                lossArray[i].setForeground(Color.BLACK);
                addGCComp(lossArray[i], rotationPanel, rotationGB, labelX, labelY, labelSize);
                labelX += 75;
                savesArray[i] = new JLabel(df.format(team.rotation.get(i).getPitcherSaves()));
                savesArray[i].setForeground(Color.BLACK);
                addGCComp(savesArray[i], rotationPanel, rotationGB, labelX, labelY, labelSize);
                labelX += 75;
                bsArray[i] = new JLabel(df.format(team.rotation.get(i).getPitcherBlownSaves()));
                bsArray[i].setForeground(Color.BLACK);
                addGCComp(bsArray[i], rotationPanel, rotationGB, labelX, labelY, labelSize);
                labelX += 75;

                labelY += 25;
            }

我错过了什么?我尝试使用GridBagConstraints.NORTHWEST作为锚点,但这似乎没有用。任何帮助将不胜感激!

干杯, 大卫

1 个答案:

答案 0 :(得分:1)

您需要创建Gridbaglayout,然后通过它添加要布局的组件。

喜欢这个

GridBagLayout layout = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();

layout.addLayoutComponent(Component, cons);

然后将布局添加到Container。