• Post Reply Bookmark Topic Watch Topic
  • New Topic

JPopupMenu

 
Wei Yuan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i wanna add two different JPopupMenu in a JScrollPane which
contain a JTree,and then add the JScrollPane in a JFrame.
i want one of the 2 menu popup when i click on the leaf of the
tree,and another popup when i click on the parent.
i have used the enableEvent(),but it didn't work.the menus did
not appear when i right the mouse.
Can any tell me why and how i can achieve what i want.
Thanks in advance.
 
Laurent Leonard
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try to use MouseListener on components
somewhereInTheInitiationOfTheObject()
{
...
popupListener = new PopupListener(); // defined later
...
}
void addMouseListenerToAllComponents(Component[] comp)
{
if (comp != null)
{
for (int i = 0; i < comp.length; i++)<br /> {<br /> comp[i].addMouseListener(popupListener);<br /> if (comp[i] instanceof Container)<br /> {<br /> Component[] subcomp = ((Container) comp[i]).getComponents();<br /> addMouseListenerToAllComponents(subcomp);<br /> } <br /> } <br /> } <br /> } <br /> void removeMouseListenerFromAllComponents(Component[] comp)<br /> {<br /> if (comp != null)<br /> {<br /> for (int i = 0; i < comp.length; i++)<br /> {<br /> comp[i].removeMouseListener(popupListener);<br /> if (comp[i] instanceof Container)<br /> {<br /> Component[] subcomp = ((Container) comp[i]).getComponents();<br /> removeMouseListenerFromAllComponents(subcomp);<br /> } <br /> } <br /> } <br /> } <br /> // A inner class<br /> class PopupListener extends MouseAdapter<br /> {<br /> public void mousePressed(MouseEvent evt)<br /> {<br /> maybeShowPopup(evt);<br /> } <br /> private void maybeShowPopup(MouseEvent evt)<br /> {<br /> if (evt.getModifiers() == evt.BUTTON3_MASK) // right click<br /> {<br /> // you must test the source of the event <br /> if(evt.getSource() == aLeaf) // a reference to the source<br /> {<br /> popupMenuForLeaf.pack();<br /> int h = (int)popupMenuForLeaf.getPreferredSize().getHeight();<br /> int w = (int)popupMenuForLeaf.getPreferredSize().getWidth();<br /> int x = evt.getX();<br /> int y = evt.getY();<br /> Dimension frameSize = yourFrame.this.getSize(); // or something else<br /> if ((x+w/2) > frameSize.getWidth()/2)<br /> {<br /> x -= w;<br /> }<br /> if ((y+h/2) > frameSize.getHeight()/2)
{
y -= h;
}
popupMenuForLeaf.show(evt.getComponent(), x, y);
}
if(evt.getSource() == aRoot) // for example
{
the other case
}
}
}
}


------------------
Laurent Leonard
Laurent.Leonard@advalvas.be
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!