gpt4 book ai didi

java - 将 JMenuItem 置于 JPopupMenu 中心

转载 作者:行者123 更新时间:2023-12-02 01:28:16 29 4
gpt4 key购买 nike

我想要做的是将 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);

最佳答案

阅读 JMenuItem API。

JMenuItem 扩展自 AbstractButton

AbstractButtonJButtonJCheckBoxJMenuItem 等 Swing 组件的基类。因此,它提供了自定义文本、图标等显示的方法。

开头:

setHorizontalAlignment(...)

但也请查看其他可用的方法以供将来引用。

关于java - 将 JMenuItem 置于 JPopupMenu 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56526893/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com