Reputation: 41
What I want to do is to center the JMenuItem elements inside the JPopupMenu. This is how they currently appear
I would like them to be in the center instead of the left side.
Here are some parts of my code
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);
Upvotes: 0
Views: 141
Reputation: 324137
Read the JMenuItem
API.
JMenuItem
extends from AbstractButton
.
AbstractButton
is the base class for Swing components like JButton
, JCheckBox
, JMenuItem
. As such it provides methods to customize the display of the text, icon etc.
Start with:
setHorizontalAlignment(...)
But check out the other methods available for future reference as well.
Upvotes: 2