简体   繁体   中英

How do I center a Component in a JPanel without using BorderLayout? - Java

I think, that you can center a Component (for Example a JButton ) in a JPanel , using the BorderLayout :

panel.setLayout(new BorderLayout());
panel.add(button, BorderLayout.CENTER);

But than the JButton takes up all the space in the JPanel .

Is it for example possible to use another LayoutManager , or is there an even easyer way to do center the JButton ?

I think, button.setAlignmentX(JButton.CENTER_ALIGNMENT) doesn't work.

I guess with most tasks it's just a matter of personal choice/your boss's order if you're using a Layout manager rather than the others. There are some Layout managers that can accomplish quite every requirement, such as GridBadLayout, but i personally think that in most situation they're not the best choice since they might end up overcomplicating things. For this specific task i would go with a BoxLayout https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html

And would code something like:

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

public class CenteredButton extends JFrame {

    public CenteredButton() {
        Container pane = getContentPane();
        pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));

        JPanel panel = new JPanel();
        JButton button = new JButton("Button1");
        button.setPreferredSize(new Dimension(100, 50));

        panel.add(button);

        pane.add(panel);

        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new CenteredButton();
    }
}

As you may notice, resizing the button's dimension will not change the fact that it sticks in the middle of the frame.

PS: developers opinions are mostly enthusiastic about http://www.miglayout.com/ and https://tips4java.wordpress.com/2008/11/02/relative-layout/ . Both of these, in my opinion, are easier to manage than GridBagLayout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM