JPopupMenu Problem

Is there an easier way to code a JPopupMenu?
I keep having trouble with mine. It does not display the Popup menu correctly when I run the Java program.
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PopupTest {
    private JFrame frame;
    private JPopupMenu popup;
    public PopupTest() {
          frame = new JFrame("My Frame");
          popup = new JPopupMenu();
          popup.add("mi1");
          popup.add("mi2");
          frame.addMouseListener(new MouseAdapter() {
              public void mousePressed(MouseEvent me) {
                    if (me.isPopupTrigger()) {
                       popup.show(me.getComponent(), me.getX(), me.getY());
              public void mouseReleased(MouseEvent me) {
                    if (me.isPopupTrigger()) {
                        popup.show(me.getComponent(), me.getX(), me.getY());
         frame.getContentPane().add(popup);
          frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
          new PopupTest();
}Any code samples is much appreciated
I have looked at the Java tutorial, it is too complex or too big for my liking.
Thanks,
Riz

To bring up a popup menu ( JPopupMenu [(in the API reference documentation)] ), you must register a mouse listener on each component that the popup menu should be associated with. The mouse listener must detect user requests that the popup menu be brought up. On Windows and Motif platforms, the user brings up a popup menu by pressing the right mouse button while the cursor is over a component that is popup-enabled.
The mouse listener brings up the popup menu by invoking the show method on the appropriate JPopupMenu instance. The following code, taken from PopupMenuDemo.java [(in a .java source file)] , shows how to create and show popup menus:
//...where instance variables are declared:
JPopupMenu popup;
    //...where the GUI is constructed:
//Create the popup menu.
    popup = new JPopupMenu();
    menuItem = new JMenuItem("A popup menu item");
    menuItem.addActionListener(this);
    popup.add(menuItem);
    menuItem = new JMenuItem("Another popup menu item");
    menuItem.addActionListener(this);
    popup.add(menuItem);
    //Add listener to components that can bring up popup menus.
    MouseListener popupListener = new PopupListener();
    output.addMouseListener(popupListener);
    menuBar.addMouseListener(popupListener);
class PopupListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        maybeShowPopup(e);
    public void mouseReleased(MouseEvent e) {
        maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e) {
        if (e.isPopupTrigger()) {
            popup.show(e.getComponent(),
                       e.getX(), e.getY());
}Popup menus have a few interesting implementation details. One is that every menu has an associated popup menu. When the menu is activated, it uses its associated popup menu to show its menu items.
Another detail is that a popup menu itself uses another component to implement the window containing the menu items. Depending on the circumstances under which the popup menu is displayed, the popup menu might implement its "window" using a lightweight component (such as a JPanel), a "mediumweight" component (such as a Panel [(in the API reference documentation)] ), or a heavyweight window (something that inherits from Window [(in the API reference documentation)] ).
Lightweight popup windows are more efficient than heavyweight windows, but they don't work well if you have any heavyweight components inside your GUI. Specifically, when the lightweight popup's display area intersects the heavyweight component's display area, the heavyweight component is drawn on top. This is one of the reasons we recommend against mixing heavyweight and lightweight components. If you absolutely need to use a heavyweight component in your GUI, then you can invoke JPopupMenu.setLightWeightPopupEnabled(false) to disable lightweight popup windows. For details, see Mixing Heavy and Light Components, an article in The Swing Connection.

Similar Messages

  • JPopupMenu - Problem with Handling ESC character.

    As per the Javadoc, it says ESC is the key for retracting the PopupMenu. But it is not retracting whenever we press ESC.
    Is this a bug?
    If it is not a bug, how do i retract the popup menu when the Esc is pressed.
    Thanks,
    -Shenbugs

    I also have my JDialogs set up to close when ESC is pressed, by overriding the createRootPane() method:  protected JRootPane createRootPane()
        closeDialogAction = new CloseDialogAction();
        JRootPane rootPane = new JRootPane();
        KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        rootPane.registerKeyboardAction(closeDialogAction, stroke,
            JComponent.WHEN_IN_FOCUSED_WINDOW);
        return rootPane;
      }I tried adding a menubar to one of my dialogs (which I had never done before), and I saw the same problem as you: if I pressed escape when the menu was open, the whole dialog disappeared. But if I comment out the method above and recompile, the menubar works as it should.
    The problem is that JPopupMenu's InputMap uses a WHEN_IN_FOCUSED_WINDOW binding, which appears to be the binding of last resort (I tried the above with a WHEN_ANCESTOR_OF_FOCUSED_COMPONENT binding, with the same results). So, while we would like ESC to be interpreted as "if a menu is open, close it; otherwise close the dialog", that doesn't seem to be possible.
    In that dialog's RootPane i added a InputMap for "ESC"
    key to map that to WindowClosingEvent. And while
    running, if the popupMenu is shown, and Esc is pressed
    the Dialog is closed. And if i remove that ActionMap,
    popupMenu still remains visible though i press ESC.You say you removed the ActionMap, but did you remove the InputMap as well? If not, your RootPane is probably still consuming the ESC-key event.

  • JPopupMenu problem- Urgent

    I Have a JCalendar component which is basically a panel placed in JPopupMenu .When the user clicks on the Button the calendar gets popped up. when the user clicks again the calendat disappears. There is no problem till this point. Iam maintaing a flag based on which i decide whether to show the popup or hide it.
    My problem is when the user clicks elsewhere i.e somewhere outside the popup other than the button, the
    popup disappears as it is the normal behaviour of the JPopupMenu.But since the popup is being disabled with out the click of a button there is no means for me to reset the flag so that when the user clicks again the calendar is popped up. Because of this the user is forced to click twice on the button
    public void displayCalendar() {
    if (isCalVisible) {
    final KeyEvent myEscKE = new KeyEvent(popup, KeyEvent.KEY_PRESSED,
    (long) 0, 0, KeyEvent.VK_ESCAPE, KeyEvent.CHAR_UNDEFINED);
    new DefaultKeyboardFocusManager().dispatchKeyEvent(myEscKE);
    this.requestFocus();
    } else {
    if (popup == null) {
    popup = getPopup();
    isCalVisible = true;
    popup.add(cjCal);
    popup.show(this, 0, this.getPreferredSize().height);
    public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == downBut) {
    displayCalendar();
    So my problem is how do i set the flag for event fired outside the button? If there is a better method to do this thing suggest me?

    I also have the problem when I try to place combobox inside another popup.
    when inner combobox trys to open its popup the outer parent combobox closes its popup togeter with all its content.
    It seams that Java uses single class MenuSelectionManager to look for all opened popups. And when new one about to became opened this manager closes the others. And I do not know how to prevent that.
    If you have any idas, please let me know.

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

  • Problem with InputVerifier and JPopupMenu

    Hello, I have a problem related to the usage of InputVerifier and JPopupMenu.
    Consider the following scenario:
    - A frame composed of two components: a JTextField and a JComboBox
    - An InputVerifier that was set in the JComboBox (and in its associated JTextComponent)
    - A JPopupMenu which is enabled by a right mouse click over the components of the frame.
    The verify() method of the InputVerifier class is executed every time the focus is on the JComboBox and is requested by other component.
    Suppose that the focus is on the JComboBox, and a right mouse click is executed over this components. In summary, we have:
    1) The method verify() of the InputVerifier associated to the JComboBox is executed
    2) The focus changes from the JTextComponent (associated to the JComboBox) to the JRootPane (associated to the JTextComponent (that is associated to the JPopupMenu)).
    Now suppose that, the user clicks in the JTextField component (note that the JPopupMenu is visible and has the focus). What happens is that the focus goes from the JRootPane -> JTextComponent (associated to the JComboBox) -> JTextField.
    Despite the focus flow through the JTextComponent, the Swing plattaform, when executing the runInputVerifier() in the JComponent context, get the JRootPane component as the focusOwner instead of the JTextComponent.
    In this way, the Swing platform tries to invoke the InputVerify of the JRootPane (that is set with "null"), and the JComboBox InputVerifier is not executed as expected.
    It works as if the focus is flowing from the JRootPane directly to the JTextField.
    However, if the user clicks on the JComboBox before clicking in the JTextField, the Swing platform executes the correct InputVerifier, i.e., the one associated to the JComboBox (actually, the one associated to the JTextComponent).
    Any thoughts to solve this problem?
    Thanks

    A plus information, I am using jdk1.5.0_22.

  • Jpopupmenu visibility problem with JWindows

    Hello,
    BACKGROUND:
    I am attempting to implement a feature similar to one found in the netbeans IDE for a programming editor I am helping to write. The feature is an autocomplete/function suggestion based on the current word being typed, and an api popup for the selected function.
    Currently a JPopupMenu is used to provide a list of suggested functions based on the current word being typed. EG, when a user types 'array_s' a JPopupMenu pops up with array_search, array_shift, array_slice, etc.
    When the user selects one of these options (using the up/down arrow keys) a JWindow (with a jscrollpane embedded in it) is made visible which displays the api page for that particular function.
    PROBLEM:
    The problem is that when a user scrolls down the JWindow the JPopupmenu disappears so he user cannot select another function.
    I have added a ComponentListener to the JPopupMenu so that when componentHidden is called I can do checks to see if it should be visible and make visible if necessary. However, componentHidden is never called.
    I have added a focuslistener to the JPopupMenu so that when it loses focus I can do the same checks/make visible if necessary. This function is never called.
    I have added a popupMenuListener but this tells me when it is going to make something invisible, not actually when it's done it, so I can't call popup.setVisible(true) from popupMenuWillBecomeInvisible because at that point the menu is still visible.
    Does anyone have any suggestions about how I can scroll through a scrollpane in a JWindow whilst still keeping the focus on a separate JPopupMenu in a separate frame?
    Cheers

    The usual way to do popup windows (such as autocomplete as you're doing) is not to create a JPopupMenu, but rather an undecorated (J)Window. Stick a JList in the popup window for the user to select their choice from. The problem with using a JPopupMenu is just what you're experiencing - they're designed to disappear when they lose focus. Using an undecorated JWindow, you can control when it appears/disappears.
    See this thread for information on how to do this:
    http://forum.java.sun.com/thread.jspa?threadID=5261850&messageID=10090206#10090206
    It refers you to another thread describing how to create the "popup's" JWindow so that it doesn't steal input focus from the underlying text component. Then, further down, it describes how you can forward keyboard actions from the underlying text component to the JWindow's contents. This is needed, for example, so the user can keep typing when the autocomplete window is displayed, or press the up/down arrow keys to select different items in the autocomplete window.
    It sounds complicated, but it really isn't. :)

  • Flickerring Problem With JPopUpMenu

    Hello Friends,
    In my application made in Java i show a JPopUpmenu on a JINternalFrame in a DekstopPane which is further kept in JFrame. The contents of the PopUpMenu may vary as according to the various places where the mouse is clicked. Sometimes when the mouse may be clicked on the lower part of the applciation some part of the PopUpmenu goes out of the visible area of the screen. For that after showing the popupmenu i get the height of the popup menu and shift it accordingly so that its length doesnt go out of the viewable area. It works fine but the problem is that it gives a little flicker. And alsoo of i try to set the position before showing the pop up menu i am not able to do so because before calling the show() method of the popUPmenu i am getting the height and width of the pop up menu. Please help me out.
    Any type of pointers and links would be highly helpful.
    Thanks in Advance
    Vikram.

    HI!
    it didnt work
    here is the code snippet
              popupClass.pack();
              popupClass.requestFocus();          
              java.lang.System.out.println(" HEIGHTTTTT "+popupClass.getHeight());
              int Height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
              int Width = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
              if ((DiagramInternalPane)getParent() != null)
                   if(((mouseY+popupClass.getHeight()-((DiagramInternalPane)getParent()).GetParent().scrollpane.getVerticalScrollBar().getValue()+AsterixApplet.getFrame().getY()) > Height-160) && ((mouseX+popupClass.getWidth()-((DiagramInternalPane)getParent()).GetParent().scrollpane.getHorizontalScrollBar().getValue()+AsterixApplet.getFrame().getX()) > Width-20))
                        popupClass.show(comp,mouseX-popupClass.getWidth(), mouseY-popupClass.getHeight());
                   else
                        if((mouseY+popupClass.getHeight()-((DiagramInternalPane)getParent()).GetParent().scrollpane.getVerticalScrollBar().getValue()+AsterixApplet.getFrame().getY()) > Height-160)
                             popupClass.show(comp,mouseX, mouseY-popupClass.getHeight());
                        if((mouseX+popupClass.getWidth()-((DiagramInternalPane)getParent()).GetParent().scrollpane.getHorizontalScrollBar().getValue()+AsterixApplet.getFrame().getX()) > Width-20)
                             popupClass.show(comp,mouseX-popupClass.getWidth(), mouseY);     
              if(getParent() != null)     
                   getParent().repaint();
              popupClass.show(comp,mouseX, mouseY);                
              java.lang.System.out.println(" HEIGHTTTTT AAAAAAAAAAAAAAAA"+popupClass.getHeight());
    Before caluing the show() , method i am getting the height as 0 and only after calling the show method i am getting the actual height. Is it a java bug or something ?
    Anyway thanks for all ur help

  • Problem in Opening JPopupMenu

    Hi
    We are facing a problem in opening JPopupMenu in multiple browser windows. We have a parent window which has a JApplet. We have another window which is a child window of the parent. That also has a different applet.
    When we right click on the applet which is available in the parent window, the popup menu shows up.
    When we do the same on the child window, the popup shows up finely. Now when we select any menu item in the child window's popup, the focus goes to the parent window and then immediately comes back to the child window.
    We are not overriding any focus lost event in the applets or handling any key events. We are using JDK 1.4.1 plugin to the browser.
    I appreciate your suggestion/comments.
    Thanks,
    Murugu

    I will resate the problem described earlier.
    We have an applet which is displayed in 2 browser instances (parent/child) windows. The 2 windows have different instances of the same applet.
    Problem : When the user right clicks on the applet container, a popup menu is displayed. Keeping the popup menu display intact, when the user moves to the child window and right clicks on the applet container to display the popup menu, slight flickering happens which is to dispose the popup menu displayed in the first applet and then displays in the second applet.
    In the mouseReleased() method in the applet we are creating a new instance of JPopupMenu adding the necessary menu items and then displaying it. We have made sure that the 2 browser windows are having 2 different instances of the applet.
    Does this mean that the JVM always creates one instance of the popup menu ?? OR how to avoid this flickering problem ??
    Further to the problem mentioned above :
    1. The user right clicks on the first applet to display the popup menu.
    2. Clicks on a menu item (Currently no event is fired when the menu is selected). The popup menu will be      disposed after this operation.
    3. The user then moves to the second applet and right clicks on the second applet to display the popup menu.
    4. Now when the user presses the mouse button on the menu item, there is a focus shift from the second applet to the first applet. And when the mouse is released the focus comes back to the second applet.
    Note : There is no actionlistener is added to the menu items.
    Any one has any idea why this kind of behaviour is occurring in the applet and popup menu ??

  • Very Urgent - Problem in showing JPopupMenu using 1.4 plugin

    Hello ,
    I have a very different problem with JPopupMenu. I have developed a new PopupMenu extending the MetalComboPopup used by the MetalComboBoxUI. I have registered with the JPopupMenu for the callback methods popupMenuWillBecomeVisible && Invisible(). I have an applet which instantiates (3 instances) my JComboBox. When I run the applet using the JDK1.4 plugin, when I click the second JComboBox, the first and the second JComboBox's popups appear at the same time. I am unable to suppress the popup (i.e Only one popup should appear at a time).
    Can anybody help me out in this issue.
    If you have a solution you can email to me -> [email protected] /
    [email protected]
    Thankx in advance,
    SS

    Did you try changing the driver then?
    Please use Oracle's thin driver instead of the oci driver.
    There are many advantages of using the type 4 driver. the first and foremost being that it does not require oracle client side software on your machine. Therefore no enteries to be made in tnsnames.ora
    The thin driver is available in a jar called classes112.zip the class which implements the thin driver is oracle.jdbc.driver.OracleDriver
    the connection string is
    jdbc:oracle:thin:@<machine name>:1521:<sid>
    please try out with the thin driver and let me know.
    regards,
    Abhishek.

  • Problems with JPopupMenu

    Hi :
    I have a problems with a JPopupMenu.
    I have a JTable in a modal JDialog with some rows and I want to make some action with some rows so I make JPopupMenu visible with right click (no problem) but, when it reachs the JDialog border, it appears cut because it can't paint out of JDialog limits.
    What can I do to watch the entire JPopupMenu ? It's urgent.
    Thanks.
    Miquel

    This is because the Popupmenu is a lightweight component (which can't display beyond the borders of the window), try myPopup.setLightWeightPopupEnabled(false); that makes all popups in your app heavyweight.

  • Problem with key mnemonics in JPopupMenu

    Hello everyone...
    Since mnemonics do not work in a popup menu using Java sdk 1.3 (due to a bug), i am currently trying to implement this fuctionality myself. However i have a few problems...
    Please consider the following chunk of code:
    textAreaOut = new JTextArea(6, 0)
         protected void processKeyEvent(KeyEvent event)
    if (((event.getKeyChar() == 'T') || (event.getKeyChar() == 't')) &&
                        (textAreaOutPop.isVisible() == true) && (cutItem.isEnabled() == true))
                             if (event.getID() == KeyEvent.KEY_PRESSED)
                                  System.out.println("Cut");
                                  cutItem.doClick();
                                  textAreaOutPop.setVisible(false);
                             else event.consume();
                        else super.processKeyEvent(event);
    What i am trying to do is to get a keyEvent when the popup menu is visible and the menuItem is enabled. I put that in a proccessKeyEvent in order to override the typing of mnemonics inside the JTextArea.
    Unfortunately i am unable to make this to work, as there is a character typed into the textArea after i press the mnemonic (although the mnemonic now works). Since the proccessKeyEvent captures both KEY_PRESSED and KEY_RELEASED i added an extra if statement but that does not seem to solve the problem.
    Could please someone tell me whats wrong with my code sample? is there any better way to implement mnemonics in a JPopupMenu?
    Thanks for your time
    John

    I found a solution myself... Using the following code i make the mnemonics to work on the JPopupMenu in jdk 1.3
    textAreaOut = new JTextArea(6, 0)
                   protected void processKeyEvent(KeyEvent event)
                        if (event.isControlDown() == true)
                        menuBar.requestFocus();
                        else if (firePopupMenuItem('U', 'u', textAreaOutPop, undoItem1, event) == true);
                        else if (firePopupMenuItem('T', 't', textAreaOutPop, cutItem, event) == true);
                        else if (firePopupMenuItem('C', 'c', textAreaOutPop, copyItem1, event) == true);
                        else if (firePopupMenuItem('P', 'p', textAreaOutPop, pasteItem, event) == true);
                        else if (firePopupMenuItem('D', 'd', textAreaOutPop, deleteItem1, event) == true);
                        else if (firePopupMenuItem('A', 'a', textAreaOutPop, selectAllItem1, event) == true);
                        else if (firePopupMenuItem('S', 's', textAreaOutPop, sendItem, event) == true);
                        else if (textAreaOutPop.isVisible() == true)
                        event.consume();
                        else super.processKeyEvent(event);
    and the firePopupMenuItem mehtod...
    private boolean firePopupMenuItem(char mnemonic1, char mnemonic2, JPopupMenu puMenu,
         JMenuItem puMenuItem, KeyEvent ke)
              if (((ke.getKeyChar() == mnemonic1) || (ke.getKeyChar() == mnemonic2)) &&
              (puMenu.isVisible() == true) && (puMenuItem.isEnabled() == true))
                   //Testing
                   System.out.println("firePopupMenuItem");
                   if (ke.getID() == ke.KEY_PRESSED)
                   puMenuItem.doClick();
                   else puMenu.setVisible(false);
                   return true;
              return false;
    However, there is a small problem...
    When i use a mnemonic the event is executed and the JPopupMenu closes (which is fine) however when the popup menu is closed if i click at exactly the same point of where i clicked to open it the mouse event will not trigger and i have to do 2 clicks in order to open again the popup menu again. This is not happening if the mouse click is in different location (i.e. the popup menu opens with only 1 mouse click)...
    Anyone knows why?
    Thanks,
    John

  • Problem dismissing a JPopupMenu

    I have a DropDownCalendar class that extends JButton. I am inserting a calendar(JPanel) into a JPopupMenu. The JPopupMenu is then invoked by the user when they click on the DropDownCalendar button. When a user clicks on a date in the calendar, the dateChanged() action is called which sets the selected date and then hides the JPopupMenu. After I hide the JPopupMenu, I then have to click TWICE on the DropDownCalendar button before the mouse event is fired again to redisplay the popup. The button never receives the first mouse click, but then receives the second. I think the popup is grabbing the first mouse click. Is popup.setVisible(false) the right way to dismiss the popup?
    Here's the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.*;
    public class DropDownCalendar extends JButton {
         JLabel          dateLabel, arrowLabel;
         JPopupMenu jpm;
         SimpleCalendar scal;
         SimpleDateFormat dateFormatter;
         Dimension origin = new Dimension(0, 0);
         class MouseHandler extends MouseAdapter {
              public void mousePressed(MouseEvent me) {
                   jpm.show(me.getComponent(), 0, me.getComponent().getHeight());
    * DropDownCalendar constructor comment.
    public DropDownCalendar() {
         super();
         // Set display format to "Mon, Dec 31, 2001"
         dateFormatter = new SimpleDateFormat ("EEE, MMM d, yyyy");
         // Button contains two JLabels. One for the date string and another
         // for the up/down arrow.
         dateLabel = new JLabel("", JLabel.LEFT);
         arrowLabel = new JLabel(" \u25BC", JLabel.RIGHT);
         setMargin(new Insets(0,0,0,0));
         setLayout(new BorderLayout());
         add(dateLabel, BorderLayout.WEST);
         add(arrowLabel, BorderLayout.EAST);
         addMouseListener(new MouseHandler());
         scal = new SimpleCalendar();
         scal.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
         dateChanged();
         jpm = new JPopupMenu();
         jpm.setBorderPainted(false);
         jpm.add(scal);
         dateChanged();     // Trigger this to initialize the date string in the button
    private void dateChanged()
         // Set the date string the in the button
         dateLabel.setText(dateFormatter.format(scal.getSelection()));
         jpm.setVisible(false);

    I am having the same problem. If the JPopupMenu is visible and the user clicks somewhere else on the JPanel to select something else, the JPopupMenu goes away but the MouseEvent doesn't get called on the JPanel. The only MouseEvent I get is mouseEntered. I put a PopupMenuListener on the JPopupMenu and tried requesting focus and transfer focus to my JPanel but that doesn't work. I have noticed that it does work if the same code it applied to a JTable or JTree?? On a JTable after the popupMenuWillBecomeInVisible a mouseReleased event is fired on the JTable and it looks like it is coming from java.awt.LightweightDispatcher.retargetMouseEvent. How do I get this to work just using a JPanel?

  • Probleme on JPopupMenu with JDialog

    I use JPopupMenu with JDialog. To display the popup, I use a mousePressed in a panel of the dialog:
    public void mousePressed(MouseEvent e) {
    if( e.getClickCount()==1 && e.getModifiers()==MouseEvent.BUTTON3_MASK && ga!=null ) {
         mpopup.show(e.getComponent(),e.getX(), e.getY());
    It works fine, but when a part of the popup is out of the dialog, the popup doesn't display.
    Is it normal?
    Has someone already had this problem?
    I work with jdk1.3.1_01
    Thanks for your help
    Templ

    When you create your popup menu do this :
    mpopup.setLightWeightPopupEnabled(false);
    I hope this helps,
    Denis

  • JPopupMenu/JMenuItem sizing problem

    Hi All,
    I have a JPopupMenu that is displayed when a right-click takes place. The popup menu should display three JMenuItems when a vertex is right-clicked and one menu item when an edge is right-clicked. However, when I right-click a vertex, only two menu items are visible, and when I right-click an edge, zero menu items are visible (the popup menu appears, but it is so small that I can't see the menu item).
    Here is the relevant code:
              protected void handlePopup(MouseEvent me) {
                final VisualizationViewer vv = (VisualizationViewer)me.getSource();
                Point2D p = vv.inverseViewTransform(me.getPoint());
                PickSupport pickSupport = vv.getPickSupport();
                if(pickSupport != null) {
                    Vertex v = pickSupport.getVertex(p.getX(), p.getY());
                    Edge e = pickSupport.getEdge(p.getX(), p.getY());
                    if((v != null) && (v instanceof BrokerVertex)) {                 
                         JPopupMenu popup = new JPopupMenu();
                        JMenuItem m_SetAdvMenuItem = new JMenuItem(MonitorResources.M_SET_ADV);
                        m_SetAdvMenuItem.addActionListener(m_MonitorFrame);
                        popup.add(m_SetAdvMenuItem);
                        JMenuItem m_centerVertex = new JMenuItem("Center Vertex");
                        m_centerVertex.setAction(new CenterAction(m_graph.getLayout().getLocation(v)));
                        popup.add(m_centerVertex);
                        JMenuItem m_SetSubMenuItem = new JMenuItem(MonitorResources.M_SET_SUB);
                        m_SetSubMenuItem.addActionListener(m_MonitorFrame);
                        popup.add(m_SetSubMenuItem);
                        popup.show(vv, me.getX(), me.getY());
                        popup.pack();
                    } else if ((e != null) && (e instanceof MonitorEdge)) {
                         MonitorEdge mEdge = (MonitorEdge) e;
                         JPopupMenu popup = new JPopupMenu();
                         boolean activationCountDisplayStatus = mEdge.activationCountIsDisplayed();
                         String activationCountToggleMessage;
                         if (activationCountDisplayStatus) {
                              activationCountToggleMessage = "Hide Message Counter";
                         } else {
                              activationCountToggleMessage = "Show Message Counter";
                        JMenuItem m_activationCountMenuItem = new JMenuItem(activationCountToggleMessage);
                        m_activationCountMenuItem.setAction(new ToggleEdgeActivationCountMessageAction(mEdge));
                        popup.add(m_activationCountMenuItem);
                        popup.show(vv, me.getX(), me.getY());
                        popup.pack();
              }The problem is with the JMenuItems that use setAction instead of addActionListener (m_centerVertex and m_activationCountMenuItem). These two JMenuItems are in the popup menu list, but the popup menu is not large enough for me to see the labels given to m_centerVertex and m_activationCountMenuItem.
    Anyone know what I'm doing wrong?
    m_SetAdvMenuItem and m_SetSubMenuItem display correctly. It's as if the height of m_centerVertex and m_activationCountMenuItem are set at a value of 0 but the heights of the other two JMenuItems are the correct height.
    Message was edited by:
    themiddle

    Did you set a name value in your Actions? The name value will be used to set the text. If its null that may account for the small size of the menu item.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

Maybe you are looking for