在JPopupMenu中居中JMenuItem

时间:2019-06-10 12:58:39

标签: java swing jmenuitem

我想要做的是将JMenuItem元素居中在JPopupMenu内部。它们当前的显示方式 image

我希望它们位于中心位置而不是左侧。

这是我代码的一部分

    JButton lvlBtn = new JButton("Level"); //For the button
    JPopupMenu pmenu = new JPopupMenu();
    JMenuItem easyMenuItem = new JMenuItem("Easy");
    JMenuItem mediumMenuItem = new JMenuItem("Medium");
    JMenuItem hardMenuItem = new JMenuItem("Hard");

    lvlBtn.setBounds(750, 20, 280, 50); //Setting a location for the button

    //Making an ActionListener for the button
    ActionListener btnAction=new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                //This will make the popup menu appear


                Component b=(Component)ae.getSource();

               // Taking the location of the button on the screen
               Point p=b.getLocationOnScreen();

               // this - current frame
               // 0,0 where the popup will initially appear
               pmenu.show(this,0,0);

               // Changing the location of the JPopupMenu and placing it
               // below the lvlBtn
               pmenu.setLocation(p.x,p.y+b.getHeight());
            }
        };
    lvlBtn.addActionListener(btnAction);

    //Setting a size for each JMenuItem
    easyMenuItem.setPreferredSize(new Dimension(280, 20));
    mediumMenuItem.setPreferredSize(new Dimension(280, 20));
    hardMenuItem.setPreferredSize(new Dimension(280, 20));


    //Adding menu items in popup menu
    pmenu.add(easyMenuItem);
    pmenu.add(mediumMenuItem);
    pmenu.add(hardMenuItem);

1 个答案:

答案 0 :(得分:2)

阅读JMenuItem API。

JMenuItem源自AbstractButton

AbstractButton是诸如JButtonJCheckBoxJMenuItem之类的Swing组件的基类。因此,它提供了自定义文本,图标等显示方式的方法。

开始于:

setHorizontalAlignment(...)

但是请查看其他可用方法,以备将来参考。