gridbaglayout水平填充

csbfibhn  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(188)

我使用gridbaglayout从标签和按钮数组动态构建jpanel。我希望标签在面板尺寸被用户改变的时候可以拉伸它的宽度。我有weightx和fill约束,但这仍然不起作用。这个内部的gridbaglayout面板被另一个外部的grid layout面板所包围。
提前感谢您的意见和建议。
下面是这个案例的sc-

JPanel flowpanel = new JPanel(new GridBagLayout());
JPanel boxPanel = new JPanel(new GridLayout(2,0));

int valueCount =8;

void labelPropertySetter(JLabel label, JButton button, String name) throws IOException {
    label.setPreferredSize(new Dimension(200,55));
    label.setText(name);
    button.setPreferredSize(new Dimension(100,55)); 
    button.setName(name);
    button.setText(name);
}

public static void main (String[] args) throws IOException {
    DemoPanel dp  = new DemoPanel();
    JLabel[] numberLabel = new JLabel[dp.valueCount];
    JButton[] button = new JButton[dp.valueCount];

    for (int i=0;i<dp.valueCount;i++) {
        try {
                //jpanel[i]= new JPanel(new BorderLayout(0,0));
                numberLabel[i]=new JLabel();
                button[i]=new JButton();
                button[i].addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ((JButton)e.getSource()).setVisible(false);
                        System.out.println(((JButton)e.getSource()).getName());

                    }
                });

                dp.labelPropertySetter(numberLabel[i], button[i], new StringBuilder("Name :").append(i).toString());
                //dp.boxPanel.add(jpanel[i]);
            }
         catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
    GridBagConstraints gbc = new GridBagConstraints();

    for(int i=0;i<dp.valueCount;i++)
    {
        gbc.gridx=1;
        gbc.gridy=i;
        gbc.gridheight=1;
        gbc.gridwidth=1;
        gbc.weightx=1.0;
        gbc.fill=GridBagConstraints.HORIZONTAL;
        gbc.anchor=GridBagConstraints.CENTER;
        dp.flowpanel.add(numberLabel[i], gbc);

        gbc.gridx=2;
        gbc.gridy=i;
        gbc.gridheight=1;
        gbc.gridwidth=1;
        gbc.weightx=0;
        gbc.anchor=GridBagConstraints.LINE_END;
        dp.flowpanel.add(button[i], gbc);   
    }
    dp.boxPanel.setPreferredSize(new Dimension(500,500));
    dp.boxPanel.add(dp.flowpanel);
    dp.add(dp.boxPanel);

    dp.pack();
    dp.setVisible(true);
}
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题