title: How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame?
body: <p>Hi all!
  I'm trying to solve an -apparently- simple problem, but I cannot fix it.
  I'm working on a sample application with Java/Swing libraries; 
  I have a JFrame and a JPanel.
  I just want to achieve the following objectives:</p>
  
  <ol>
  <li><p>JPanel <em>MUST</em> be centered inside the JFrame.</p></li>
  <li><p>JPanel <em>MUST</em> have <em>ALWAYS</em> the size that is specified with<br>
  setPreferredSize() method. It MUST NOT be resized under this size.</p></li>
  </ol>
  
  <p>I tried by using a GridBagLayout: it's the <em>ONLY</em> way I can do it.</p>
  
  <p>See the sample below:</p>
  
  <pre><code>/* file StackSample01.java */
  
  import java.awt.*;
  import javax.swing.*;
  
  public class StackSample01 {
      public static void main(String [] args) {
  
          JFrame frame = new JFrame();
          JPanel panel = new JPanel();
          panel.setPreferredSize(new Dimension(100, 100));
          panel.setBackground(Color.RED);  
  
          frame.setLayout(new GridBagLayout());
          frame.add(panel, new GridBagConstraints());
          frame.setSize(new Dimension(200, 200));
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
  
      }
  }
  </code></pre>
  
  <p><a href="http://i1141.photobucket.com/albums/n589/IT00/Screenshot01.png">Here</a> a screenshot: </p>
  
  <p>I would not use a GridBagLayout to do a thing too simple.
  I tried a simplest solution, by using a Box, but this does not work:</p>
  
  <p>Sample code:</p>
  
  <pre><code>/* file StackSample02.java */
  
  import java.awt.*;
  import javax.swing.*;
  
  public class StackSample02 {
      public static void main(String [] args) {
  
          JFrame frame = new JFrame();
          JPanel panel = new JPanel();
          panel.setPreferredSize(new Dimension(100, 100));
          panel.setBackground(Color.RED); // for debug 
  
          panel.setAlignmentX(JComponent.CENTER_ALIGNMENT); // have no effect
  
          Box box = new Box(BoxLayout.Y_AXIS);
  
          box.add(Box.createVerticalGlue());
          box.add(panel);     
          box.add(Box.createVerticalGlue()); // causes a deformation
  
          frame.add(box);
          frame.setSize(new Dimension(200, 200));
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
  
      }
  }
  </code></pre>
  
  <p><a href="http://i1141.photobucket.com/albums/n589/IT00/Screenshot02.png">Here</a> a screenshot, </p>
  
  <p>Any ideas? Thanks to all :-)</p>