How to disable a JPopupMenu

Hi,

I am using Java 6.

A JPopupMenu is set to a JTextField. Everytime the user right-clicks in the textfield the popup menu shows. However in some cases the popup menu shall not show. Please consider the following pseudo code:

JPopupMenu popup =new JPopupMenu();

popup.add(anAction);

JTextField tf =new JTextField();

tf.setComponentPopupMenu(popup);

If the textField is disabled the popup should not show when user right-clicks:

tf.setEnabled(false);

tf.getComponentPopupMenu().setEnabled(false);

I thought this would be the way to disable the popup but it does not work. Any help is appreciated.

Thx.

[809 byte] By [squibbera] at [2007-11-27 9:53:26]
# 1

You may have to override the show and/or setVisible methods of the JPopupMenu to check if the component that invoked it is enabled before showing. Here is some pseudo code

JPopupMenu popup = new JPopupMenu() {

public void show(Component c, int x, int y) {

if(!c.isEnabled()) {

return;

}

super.show(c,x,y);

}

};

popup.add(anAction);

JTextField tf = new JTextField();

tf.setComponentPopupMenu(popup);

ICE

icewalker2ga at 2007-7-13 0:22:41 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thx for your help! To override the show method came to my mind too and I know it works. But I am still not sure if this is the standard way to go to enable/disable a JPopupMenu because actually it is not disabled by overriding the show method - it is just not shown. squibber
squibbera at 2007-7-13 0:22:41 > top of Java-index,Desktop,Core GUI APIs...
# 3

> actually it is not disabled by overriding the show method - it is just not shown

True that. I don't know if there is a "standard" way to disable a JPopupMenu, but I always say, it is not about standards when initially presented with a problem, but solutions. If it works for now fine, later if a standard and more efficient way of getting around the problem surfaces then we swtich to that.

ICE

icewalker2ga at 2007-7-13 0:22:41 > top of Java-index,Desktop,Core GUI APIs...
# 4
I don't use JDK5, but presumable you can remove the popup by using:tf.setComponentPopupMenu(null);
camickra at 2007-7-13 0:22:41 > top of Java-index,Desktop,Core GUI APIs...