Pedro Duque Vieira

About Pedro Duque Vieira

Pedro DV is a Software Engineer and self taught designer with 7 years experience in user interface/front end development. He's also the co-creator of Modellus, an hobby project.

PopupMenu in JavaFX 2

Creating Popup Menus

To create a Popupmenu in JavaFX you can use the ContextMenu class.

You add MenuItems to it and can also create visual separators using SeparatorMenuItem.

In the example below I’ve opted to subclass ContextMenu and add the MenuItems on its constructor.

public class AnimationPopupMenu extends ContextMenu{
public AnimationPopupMenu()
{
(...)
  getItems().addAll(
    MenuItemBuilder.create()
    .text(ADD_PARTICLE)
    .graphic(createIcon(...))
    .onAction(new EventHandler() {
    @Override
    public void handle(ActionEvent actionEvent) {
      // some code that gets called when the user clicks the menu item
    }
    })
    .build(),

(...)
    SeparatorMenuItemBuilder.create().build(),
    MenuItemBuilder.create()
    .text(ADD_DISTANCE_MEASURER)
    .onAction(new EventHandler() {
    @Override
    public void handle(ActionEvent actionEvent) {
      // Some code that will get called when the user clicks the menu item
    }
  })
  .graphic(createIcon(...))
  .build(),
(...)
  );
}
  • Line 5: I get the Collection of children of the ContextMenu and call addAll to add the MenuItems;
  • Line 6: Uses the MenuItem builder do create a MenuItem;
  • Line 7: Passes in the text of the menu item. Variable ADD_PARTICLE is equal to “Add Particle”;
  • Line 8: Calls graphic which receives the menu item icon returned by createIcon:
    ImageView createIcon(URL iconURL)
        {
            return ImageViewBuilder.create()
                                   .image(new Image(iconURL.toString()))
                                   .build();
        }
    
  • Line 9: onAction receives the event handler which will be called when the user clicks the menu item;
  • Line15: Finally the MenuItem gets created by executing build() on the MenuItemBuilder class;
  • Line18: Creates The Separator which you can see on the figure on the start of this post. It’s the dotted line between “Add Origin” and “Add Distance Measurer”;
  • The other lines of code just repeat the same process to create the rest of the menu items.



Using JavaFX Popup Menus inside JFXPanel
If your embeding a JavaFX scene in a Swing app you’ll have to do some extra steps manually, if you don’t there won’t be hover animations on the popup menu and it won’t get dismissed automatically when the user clicks outside of it. There is a fix targeted at JavaFX 3.0 for this – http://javafx-jira.kenai.com/browse/RT-14899
First you’ll have to request the focus on the javafx container so that the popup gets hover animations and when you click outside your app window it gets dismissed. In my case I pass a reference to the javafx swing container on the construtor of the popup menu, then I’ve overwritten the show method of ContextMenu so as to request the focus on the swing container before actually showing the popup:

public void show(Node anchor, MouseEvent event)
{
  wrapper.requestFocusInWindow();
  super.show(anchor, event.getScreenX(), event.getScreenY());
}

And lastly you’ll have to also dismiss the popup when the user clicks inside the javafx scene but outside of the popup by calling hide().
I almost forgot.. thanks to Martin Sladecek (Oracle JavaFX team) for giving me some pointers.

Reference: PopupMenu in JavaFX 2 from our JCG partner Pedro Duque Vieira at the Pixel Duke blog.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Leave a Reply


8 + five =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books