I have a simple Class StatPanel that extends JPanel and has a few JTextFields, a JCheckBox, and a couple JLabels. The panel is going to be used as a series of panels used to display information and allow the user to edit the data in some of the JTextFields and I will probably have about 40 of them all stacked together on the side of the program in a JScrollPane JPanel. The layout I am using is a GridLayout(0,1).

I have them working but when the are in the scroll panel they are spaced too far apart vertically. I have tried changing the margins, changing the spacing in the GridLayout and changing the margins of the various items. Nothing I do seems to make them closer.

This is the constructor for the StatPanel class:

    public StatPanel(String statName, String statAbility){
        super();
        this.skillName = statName;
        this.setAlignmentY(CENTER_ALIGNMENT);
        isClassSkill = new JCheckBox();
        statLabel = new JLabel(skillName);
        statTotalField = new JTextField(maxLength + 1);
        statTotalField.setHorizontalAlignment(JTextField.CENTER);
        statAbilityLabel = new JLabel("= " + statAbility + " ");
        statAbilityModField = new JTextField(maxLength);
        statAbilityModField.setHorizontalAlignment(JTextField.CENTER);
        statSeperator1 = new JLabel(" + ");
        statRanksField = new JTextField(maxLength);
        statRanksField.setHorizontalAlignment(JTextField.CENTER);
        statSeperator2 = new JLabel(" + ");
        statMiscModField = new JTextField(maxLength);
        statMiscModField.setHorizontalAlignment(JTextField.CENTER);

        this.add(isClassSkill);
        this.add(statLabel);
        this.add(statTotalField);
        this.add(statAbilityLabel);
        this.add(statAbilityModField);
        this.add(statSeperator1);
        this.add(statRanksField);
        this.add(statSeperator2);
        this.add(statMiscModField);
    }
}

When I use it in the program it looks like this:

screenshot

As I am going to stack so many of them I want them pretty much one on top of the other but I can seem to remove the gap between them.

How is this done?

Thank you for your help.

有帮助吗?

解决方案

Check out the FlowLayout API. By default a JPanel uses a FlowLayout with default horizontal/vertical gap of 5 pixels. You will want to change the vertical gap used by the layout manager. So at the top of your method you will want to add:

setLayout( new FlowLayout(...) );

Edit:

Once you change the gap you will also lose the gap at the top/bottom of the main panel so you might want to add an EmptyBorder to the panel.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top