How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame?

前端 未结 6 2065
死守一世寂寞
死守一世寂寞 2020-12-03 03:27

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 JPan

6条回答
  •  被撕碎了的回忆
    2020-12-03 03:50

    First of all, thanks to all.

    I reply another time to my own question, to show everyone the choice I have made. See the sample code below; As you can see, I have included only minimal steps which are absolutely necessary to achieve the goal.

    /* file StackResponse.java */
    
    import java.awt.*;
    import javax.swing.*;
    
    public class StackResponse {
        public static void main(String [] args) {
    
            JPanel panel = new JPanel();
            Dimension expectedDimension = new Dimension(100, 100);
    
            panel.setPreferredSize(expectedDimension);
            panel.setMaximumSize(expectedDimension);
            panel.setMinimumSize(expectedDimension);
    
            panel.setBackground(Color.RED); // for debug only
    
            Box box = new Box(BoxLayout.Y_AXIS);
    
            box.add(Box.createVerticalGlue());
            box.add(panel);     
            box.add(Box.createVerticalGlue());
    
            JFrame frame = new JFrame();
            frame.add(box);
            frame.setSize(new Dimension(200, 200));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            frame.setMinimumSize(frame.getMinimumSize());   // cannot be resized-
    
            frame.setVisible(true);
    
        }
    }
    

    Here you can see a screenshot.

    Problem solved. Many thanks again to all.

    IT

提交回复
热议问题