Centering Panel in Java

跟風遠走 提交于 2019-12-14 03:17:52

问题


For some reason i am having problems centering my panel vertically that is located inside another panel. I do exactly as the examples i studied but still no luck.

Down there is my code. Despite using setAlignmentY(0.5f) on my container panel, it still wont center when i resize the window.

Also the components inside container panel wont center either, despite setAligenmentX(0.5f).

I wonder if there is a solution for this, I pretty much tried everything out there but couldnt find a solution.

JLabel idLabel;
    JLabel passLabel;
    JTextField id;
    JTextField pass;
    JButton enter;
    JPanel container;

    public JournalLogin()
    { 
        //setLayout(new FlowLayout());
        //setPreferredSize(new Dimension(500, 500));
        //setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));


        container = new JPanel();
        container.setLayout(new MigLayout());
        container.setAlignmentX(0.5f);
        container.setAlignmentY(0.5f);
        container.setPreferredSize(new Dimension(300, 300));
        container.setBorder(BorderFactory.createTitledBorder("Login"));
        add(container);

        idLabel = new JLabel("ID:");
        idLabel.setAlignmentX(0.5f);
        container.add(idLabel);

        id = new JTextField();
        id.setText("id");
        id.setAlignmentX(0.5f);
        id.setPreferredSize(new Dimension(80, 20));
        container.add(id, "wrap"); 

回答1:


setAlignmentX and Y are not the way to go about doing this. One way to center a component in a container is to have the container use GridBagLayout and to add the component without using any GridBagConstraints, a so-called default addition. There are other ways as well.

For example to alter Nick Rippe's example (1+ to him):

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;

import javax.swing.*;

public class UpdatePane2 extends JPanel {
   private static final int PREF_W = 300;
   private static final int PREF_H = 200;

   public UpdatePane2() {
      JPanel innerPanel = new JPanel();
      innerPanel.setLayout(new BorderLayout());
      innerPanel.add(new JLabel("Hi Mom", SwingConstants.CENTER), 
            BorderLayout.NORTH);
      innerPanel.add(new JButton("Click Me"), BorderLayout.CENTER);

      setLayout(new GridBagLayout());
      add(innerPanel);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("UpdatePane2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new UpdatePane2());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}



回答2:


Alignments tend to be pretty picky in Swing - they do [usually] work... but if all you're looking for is a panel that's centered, I'd recommend using Boxes in the BoxLayout (My personal favorite LayoutManager). Here's an example to get you started:

import java.awt.Dimension;
import javax.swing.*;

public class UpdatePane extends JPanel{

    public static void main(String... args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                //Create Buffers
                Box verticalBuffer = Box.createVerticalBox();
                Box horizontalBuffer = Box.createHorizontalBox();

                verticalBuffer.add(Box.createVerticalGlue()); //Top vertical buffer
                verticalBuffer.add(horizontalBuffer);

                horizontalBuffer.add(Box.createHorizontalGlue()); //Left horizontal buffer

                //Add all your content here
                Box mainContent = Box.createVerticalBox();
                mainContent.add(new JLabel("Hi Mom!"));
                mainContent.add(new JButton("Click me"));
                horizontalBuffer.add(mainContent);

                horizontalBuffer.add(Box.createHorizontalGlue());  //Right horizontal buffer
                verticalBuffer.add(Box.createVerticalGlue()); //Bottom vertical buffer


                // Other stuff for making the GUI
                verticalBuffer.setPreferredSize(new Dimension(300,200));
                JFrame frame = new JFrame();
                frame.add(verticalBuffer);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);

            }
        });
        }

}



回答3:


You will need to get the LayoutManager to center the layout for you. Currently it looks like the implementation of "MigLayout" does not honor the Alignment. Try changing it or creating a subclass.



来源:https://stackoverflow.com/questions/11835689/centering-panel-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!