Pepijn Schmitz
Pepijn Schmitz

Reputation: 2273

What's the best way to add static text to a Java Swing menu?

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:

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

Answers (2)

Ti Strga
Ti Strga

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

Denis Zaikin
Denis Zaikin

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

Related Questions