Search code examples
javaswingjlabeljpopupmenu

Center JLabel within JPopupMenu


I know this is me being completely ocd, but I am having an issue centering the JLabel text within the JPopupMenu.

I've tried popup.add(new JLabel("Menu",JLabel.CENTER)); and label.setHorizontalAlignment(SwingConstants.CENTER); label.setHorizontalTextPosition(SwingConstants.CENTER)); but no luck.

pic

Anyone know a fix?


Solution

  • Set the proper layout of the JPopupMenu such as BoxLayout, FlowLayout etc. and add the JLabel that is positioned based on the layout manager.

    Sample code:

    JPopupMenu popup = new JPopupMenu();
    popup.setLayout(new FlowLayout(FlowLayout.CENTER));
    popup.add(new JLabel("Menu"));
    

    Read more about A Visual Guide to Layout Managers where each layout is explained in details along with sample code.