GridBagLayout 的第一个按钮比其他按钮大

问题描述

我正在开发一个 Swing 应用程序,但我在使用 GridBagLayout 时遇到了一个大问题。 程序在BorderLayout中的滚动窗格中动态添加按钮,但是当我调整窗口大小时,第一个按钮变得比其他按钮大,为什么?

    setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100,100,450,300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(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);
        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)