我使用gridbaglayout从标签和按钮数组动态构造JPANEL。我希望标签在用户更改面板尺寸时拉伸其宽度。我有权重和填充限制,但仍然无法正常工作。这个内部Gridbaglayout面板被另一个网格布局的外部面板包围。
提前感谢您的意见和建议。
以下是此案例的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);
}
}