我正在开发一个Swing应用程序,我对GridBagLayout有一个很大的问题。该程序在 BorderLayout 中的滚动窗格中添加动态按钮,但是当我调整窗口大小时,第一个按钮比其他按钮大,为什么?
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(140, 2));
contentPane.add(scrollPane, BorderLayout.WEST);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0};
gbl_panel.rowHeights = new int[]{0};
gbl_panel.columnWeights = new double[]{Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{Double.MIN_VALUE};
panel.setLayout(gbl_panel);
int counter=0;
for(String nomeNazione:nazioni)
{
btn = new JButton(nomeNazione);
GridBagConstraints gbc_btn = new GridBagConstraints();
gbc_btn.insets = new Insets(0, 0, 0, 0);
gbc_btn.gridx = 0;
gbc_btn.gridy = counter;
gbc_btn.fill = GridBagConstraints.BOTH;
gbc_btn.weighty=1;
panel.add(btn, gbc_btn);
counter++;
}
在我看来,您正在尝试向滚动窗格添加相同大小的按钮。
最简单的方法是使用带有GridLayout的面板。
然后使用包装面板,以便在将包装面板添加到滚动窗格时考虑按钮的高度。向面板添加按钮时,将根据需要显示滚动条。
基本逻辑是:
JPanel buttonsPanel = new JPanel( new GridLayout(0, 1) );
buttonsPanel.add(...); // loop to add your buttons
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(buttonsPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane( wrapper );
frame.add(scrollPane, BorderLayout.LINE_START)