开发者

GridBagLayout within JScrollPane not resizing properly

I have a JPanel with a GridBagLayout inside of a JScrollPane. I also have an 'add' button with开发者_高级运维in the JPanel which, when clicked, will be removed from the JPanel, adds a new instance of a separate component to the JPanel, then adds itself back to the JPanel. This sort of makes a growing list of components, followed by the 'add' button.

Adding new components works fine, the JPanel stretches to accommodate the new components, and the JScrollPane behaves as expected, allowing you to scroll through the entire length of the JPanel.

This is how the add works:

jPanel.remove(addButton);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
jPanel.add(new MyComponent(), c);
jPanel.add(addButton, c);
jPanel.validate();
jPanel.repaint();`

Removal works by clicking a button inside the added components themselves. They remove themselves from the JPanel just fine. However, the JPanel keeps it's stretched-out size, re-centering the list of components.

This is how removal works:

Container parent = myComponent.getParent();
parent.remove(myComponent);
parent.validate();
parent.repaint();`

The question is, why does my GridBagLayout JPanel resize when adding components, but not when removing components?


You have to revalidate and repaint the JScrollPane, here is an example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingTest {

    public static void main(String[] args) {
        final JPanel panel = new JPanel(new GridBagLayout());

        for (int i = 0; i < 25; i++) {
            JTextField field = new JTextField("Field " + i, 20);

            GridBagConstraints constraints = new GridBagConstraints();
            constraints.gridy = i;

            panel.add(field, constraints);
        }

        final JScrollPane scrollPane = new JScrollPane(panel);

        JButton removeButton = new JButton("Remove Field");
        removeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (panel.getComponentCount() >= 1) {
                    panel.remove(panel.getComponentCount() - 1);
                    scrollPane.revalidate();
                    scrollPane.repaint();
                }
            }
        });


        JFrame frame = new JFrame("Swing Test");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setSize(640, 480);
        frame.setLocation(200, 200);
        frame.getContentPane().add(scrollPane);
        frame.getContentPane().add(removeButton, BorderLayout.SOUTH);

        frame.setVisible(true);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜