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

前端 未结 6 2064
死守一世寂寞
死守一世寂寞 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条回答
  •  猫巷女王i
    2020-12-03 03:55

    create a panel by name "FixedPanel" with GridBagLayout and set preferred size to frame size then add your frame into FixedPanel.

    Frame = new JFrame("CenterFrame");         
    Frame.setLocation(0, 0);
    Frame.setSize(new Dimension(400,400));//dim
    
    JPanel FixedPanel = new JPanel(new GridBagLayout());
    FixedPanel.setPreferredSize(Frame.getSize());
    
    JPanel myPanel = new JPanel();
    myPanel.setPreferredSize(new Dimension(100,100));
    myPanel.setBackground(Color.BLACK);
    
    FixedPanel.add(myPanel);
    Frame.add(FixedPanel);
    Frame.setVisible(true);  
    

提交回复
热议问题