0

I searched the site and couldn't find what I'm looking for. I tried the setAlignmentX(JSpinner.CENTER_ALIGNMENT) method of JSpinner, and also tried to set the preferred width to 10, but it did not work. I want JSpinners horizontally centered at Jpanel.

Here's my code:

 JPanel panel = new JPanel();
 panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
 JSpinner[] spinners = new JSpinner[10];

    for (int i = 0; i < spinners.length; i++) {
        spinners[i] = WidgetFactory.createJSpinnerAndAddToPanel(panel);
    }

    frame.add(panel, BorderLayout.CENTER);

and its WidgetFactory:

public static JSpinner createJSpinnerAndAddToPanel(JPanel panel) {
    JSpinner spinner = new JSpinner();
    Dimension preferredSize = spinner.getPreferredSize();
    preferredSize.width = 10;
    spinner.setPreferredSize(preferredSize);
    spinner.setAlignmentX(JSpinner.CENTER_ALIGNMENT);
    panel.add(spinner);
    return spinner;
}

This is what I get:

this is what i get

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
f.mike
  • 5
  • 2

1 Answers1

3

A BoxLayout will grow the component to the space available. To prevent the spinner from growing you need to control the maximum size:

JSpinner spinner=new JSpinner()
{
    @Override
    public Dimension getMaximumSize()
    {
        return getPreferredSize();
    }
};

You don't need the set alignment because the default is center alignment for a spinner.

//spinner.setPreferredSize(preferredSize);

Note, it is not a good idea to control the preferred size. Let each LAF determine the appropriate size.

camickr
  • 321,443
  • 19
  • 166
  • 288