Do more with JPopupMenu

Java Swing’s JPopupMenu is very versatile for displaying any type of information. It can be used for more than just display a popup menu. JPopupMenu inherits all the features of java.awt.Container including the ability to set a LayoutManager and add one or more arbitrary java.awt.Component.

Below are two examples demonstrating how to use a JPopupMenu to “popup” more complex components. The first show a popup with an array of buttons and the second example shows a popup whose content is a table.

Example 1: Instead of showing menu items, we can substitute them with buttons for a different look.

    private void showPopupMenu1(JButton invoker) {
        JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.setLayout(new GridLayout(4, 1));
        popupMenu.add(new JButton("Apple"));
        popupMenu.add(new JButton("Banana"));
        popupMenu.add(new JButton("Carrot"));
        popupMenu.add(new JButton("Orange"));
      , 0, invoker.getHeight());

Example 2: Shows a table as the main content of a JPopupMenu.

    private void showPopupMenu2(JButton invoker) throws IOException {
        JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.setLayout(new BorderLayout());
        JTable table = new JTable(createTableModel());
        popupMenu.add(new JScrollPane(table));
        Dimension preferredSize = table.getPreferredSize();
        preferredSize.width += 30;
        preferredSize.height += 30;
        table.setPreferredScrollableViewportSize(preferredSize);, 0, invoker.getHeight());