Search code examples
javaswingjoptionpanejpopupmenu

JPopupMenu auto hide on JoptionPane Confirmdialog


I know that in order to prevent JOptionpane from hiding behind any of the frame we have to give the current frame as parent frame to JOptionpane.

I have a JTree with popupmenu

it has popup menu follows

Add
Rename
Delete
when I click the delete menu i'll call the showDeleteConfirmation() to confirm the action to delete or not

But the problem if I use currentMainframe(the one which jtree is present) as parent frame for JOptionpane and when I click the JPopumenu is not hiding(still in focus) so I have to click on Joptionpane once (to hide the popupmenu) and then only I can select the options

If I use null as parentframe it is working perfectly(onclicking the the menuitem it is automatically hiding).

How to solve the issue

 //Have to click anywhere on JOptionpane to gain focus(also to hide popupmenu)
 public static Boolean showDeleteConfirmation() {
    if (deleteConfirmation) {
        int value = JOptionPane.showConfirmDialog(currentMainFrame, "Are you sure want to delete?", "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
        return value == JOptionPane.YES_OPTION;
    }
    return true;
}


//This is working perfectly
  public static Boolean showDeleteConfirmation() {
    if (deleteConfirmation) {
        int value = JOptionPane.showConfirmDialog(null, "Are you sure want to delete?", "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
        return value == JOptionPane.YES_OPTION;
    }
    return true;
}

Solution

  • I manually called JPopupmenu.hide() before calling that function.It solved the problem