Reputation: 2273
I want to include some static text in a popup menu. I'd like it to look just like any other menu item, just not selectable. Ways I have tried:
Add a disabled JMenuItem to the menu. While this results in the correct font and alignment, it causes the text to be rendered in light grey and be almost unreadable.
Add a JLabel to the menu. This looks ugly; the label uses a different font than the regular menu items, and is not aligned the same (the menu items leave space for an icon to the left, the label does not do that).
JPopupMenu popupMenu = new JPopupMenu();
JLabel label = new Label("Static text);
popupMenu.add(label);
JMenuItem menuItem = new JMenuItem("Disabled menu item);
menuItem.setEnabled(false);
popupMenu.add(menuItem);
menuItem = new JMenuItem("Regular item);
popupMenu.add(menuItem);
Am I missing some other way to add static text to a menu which uses the same font and alignment as a regular menu item, but is unselectable, does not accept the keyboard focus and is not highlighted when the mouse hovers over it?
Upvotes: 1
Views: 3992
Reputation: 1390
Years too late for the OP, but a simple way of achieving the same thing without having to fiddle around with L&F guesswork is to remove the event listener that highlights the button when the mouse is passing over it.
JMenuItem menuItem = ......
if (menuItem.getModel() instanceof DefaultButtonModel) {
DefaultButtonModel model = (DefaultButtonModel)menuItem.getModel();
model.setArmed(false);
for (ChangeListener cl : model.getChangeListeners()) {
//System.err.format("yep, removing %s%n", cl);
model.removeChangeListener(cl);
}
}
menuItem.setFocusable(false);
menuItem.setForeground ....
menuItem.setBackground ....
menuItem.setFont ....
menuItem.setHorizontalAlignment ....
Note that this is somewhat extreme, in that if there were any other event listeners registered on the "button which is now a label", they'll be nuked as well, and there's no meaningful way to tell them apart.
You can also do a JLabel
, but then of course you'll need to do a lot of the positioning and drawing that the JMenuItem
/AbstractButton
code and L&F would have done for you.
(And don't be misled by the "rollover" functionality in Swing; it would normally be exactly for this kind of thing, but is not used in menus and menu items.)
Upvotes: 2
Reputation: 579
The following works fine for me. Just add JLabel to JPanel and add JPanel to your JPopupMenu
JPanel panelLabel = new JPanel();
JLabel lblSomeText = new JLabel("Some text");
lblSomeText.setFont(menuItem.getFont());
lblSomeText.setForeground(menuItem.getForeground());
panelLabel.add(lblSomeText);
popupMenu.add(panelLabel);
Upvotes: 1