3

For a project we want to create a button which will make a tiny menu when it is clicked (the way it works is similar to back button's drop-down menu in Firefox although the way to activate is a simple left click). Only real constraint is that it has to be in Java (preferably swing if possible). So, any ideas, examples, codes on how to do it?

2
  • 4
    Okay. So what's the question? Commented Apr 24, 2011 at 18:33
  • How do you do it? I'll fix the question. Commented Apr 24, 2011 at 20:53

5 Answers 5

13

Use a JPopupMenu. E.G.

PopUpMenuDemo.java

import java.awt.event.*;
import javax.swing.*;

class PopUpMenuDemo {

    public static void main(String[] args) {

        Runnable r = new Runnable() {
            public void run() {
                final JButton b = new JButton("Pop Up");

                final JPopupMenu menu = new JPopupMenu("Menu");
                menu.add("A");
                menu.add("B");
                menu.add("C");
                b.addActionListener( new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        menu.show(b, b.getWidth()/2, b.getHeight()/2);
                    }
                } );
                JOptionPane.showMessageDialog(null,b);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

Screenshot

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

I would probably do it like this:

    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnClickMe = new JButton("Click me");
    btnClickMe.setBounds(10, 30, 89, 23);
    frame.getContentPane().add(btnClickMe);

    final JPopupMenu menu = new JPopupMenu();

    JMenuItem item1 = new JMenuItem("Item1");
    JMenuItem item2 = new JMenuItem("Item2");
    JMenuItem item3 = new JMenuItem("Item3");

    menu.add(item1);
    menu.add(item2);
    menu.add(item3);

    btnClickMe.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent e){
            if ( e.getButton() == 1 ){ // 1-left, 2-middle, 3-right button
                menu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    });

2 Comments

"I would probably do it like this: .. " btnClickMe.setBounds(10, 30, 89, 23);. Feel free to avoid giving advice until the THC clears. 1) It should not be necessary to set the size of components (in most cases, & certainly in this one). 2) By adding only a MouseListener to the button, you lose the ability to activate the button with the keyboard. I Sentence you to 2 weeks with no mouse. Officers, take the offender away.
@Andrew The code for button and frame is just a drag-n-drop in windowbuilder. The important part is the mouse event handling in combination with a popup menu. Fell free to ignore that part if it harms you in any mental way. About choosing mouselistener, the question asked about a mouse click and I thought this perspective could be useful for cases when you need to identify a certain mouse click(hence the comment about button value identification).
2

This is the code for menuButton, it looks like a button, and when you click on it a menu appears. You can customize it by adding the image icon to the menu and by methods:

setFocusable(false);
setBorderPainted(false); 
setOpaque(false); 

If you want to get it like FireFox then set the icon for the menu and call the above methods, and then set the rollover icon, selected icon & rollover selected icon.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class menuButton extends JFrame
{    
    JMenuBar fileMenuBar,editMenuBar;
    JMenu fileMenu,editMenu;
    JMenuItem newFile,open,save,saveas,exit;
    JMenuItem cut,copy,paste,undo,redo;

    public menuButton()
    {
        setTitle("menu Button");    
        setSize(500,500);
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        fileMenuBar=new JMenuBar();    
        editMenuBar=new JMenuBar();
        fileMenu=new JMenu("File");
        editMenu=new JMenu("Edit");
        newFile=new JMenuItem("New");
        newFile.setAccelerator(KeyStroke.getKeyStroke('N',InputEvent.CTRL_MASK));
        open=new JMenuItem("Open");
        open.setAccelerator(KeyStroke.getKeyStroke('O',InputEvent.CTRL_MASK));
        save=new JMenuItem("Save");
        save.setAccelerator(KeyStroke.getKeyStroke('S',InputEvent.CTRL_MASK));
        saveas=new JMenuItem("Save As");
        saveas.setAccelerator(KeyStroke.getKeyStroke('A',InputEvent.CTRL_MASK));
        exit=new JMenuItem("Exit");
        exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,InputEvent.ALT_MASK));
        cut=new JMenuItem("Cut");
        cut.setAccelerator(KeyStroke.getKeyStroke('X',InputEvent.CTRL_MASK));
        copy=new JMenuItem("Copy");
        copy.setAccelerator(KeyStroke.getKeyStroke('C',InputEvent.CTRL_MASK));
        paste=new JMenuItem("Paste");
        paste.setAccelerator(KeyStroke.getKeyStroke('V',InputEvent.CTRL_MASK));
        undo=new JMenuItem("Undo");
        undo.setAccelerator(KeyStroke.getKeyStroke('Z',InputEvent.CTRL_MASK));
        redo=new JMenuItem("Redo");
        redo.setAccelerator(KeyStroke.getKeyStroke('R',InputEvent.CTRL_MASK));
        editMenu.add(cut);
        editMenu.add(copy);
        editMenu.add(paste);
        editMenu.addSeparator();
        editMenu.add(undo);
        editMenu.add(redo);    
        fileMenu.add(newFile);
        fileMenu.add(open);
        fileMenu.add(save);
        fileMenu.add(saveas);
        fileMenu.add(exit);
        fileMenuBar.add(fileMenu);
        editMenuBar.add(editMenu);
        add(fileMenuBar);        
        add(editMenuBar);
    }

    public static void main(String args[])
    {
        new menuButton();
    }
}

2 Comments

Swing GUIs should be constructed on the EDT. The first couple of times I ran your source, the frame was blank! Please use code formatting for code samples in future.
@Andrew Thompson please try to maximize the window and try again.They will be visible to you.
1

see this it may be help you

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

public class GUI implements ActionListener, MouseListener, MouseMotionListener, KeyListener {

    private final BufferedImage offscreenImage; // double buffered image
    private final BufferedImage onscreenImage;  // double buffered image
    private final Graphics2D offscreen;
    private final Graphics2D onscreen;
    private JFrame frame;                       // the top-level component
    private JPanel center = new JPanel();       // center panel

    // create a GUI with a menu, some buttons, and a drawing window of size width-by-height
    public GUI(int width, int height) {
        offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        onscreenImage  = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        offscreen = (Graphics2D) offscreenImage.getGraphics();
        onscreen  = (Graphics2D) onscreenImage.getGraphics();

        // the drawing panel
        ImageIcon icon = new ImageIcon(onscreenImage);
        JLabel draw = new JLabel(icon);
        draw.addMouseListener(this);
        draw.addMouseMotionListener(this);

        // label cannot get keyboard focus
        center.add(draw);
        center.addKeyListener(this);

        // west panel of buttons
        JPanel west = new JPanel();
        west.setLayout(new BoxLayout(west, BoxLayout.PAGE_AXIS));
        JButton button1 = new JButton("button 1");
        JButton button2 = new JButton("button 2");
        JButton button3 = new JButton("button 3");
        JButton button4 = new JButton("button 4");
        button1.addActionListener(this);
        button2.addActionListener(this);
        button3.addActionListener(this);
        button4.addActionListener(this);
        button1.setToolTipText("Click me");
        west.add(button1);
        west.add(button2);
        west.add(button3);
        west.add(button4);

        // menu
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menuBar.add(menu);
        JMenuItem menuSave = new JMenuItem(" Save...   ");
        menuSave.addActionListener(this);
        menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        menu.add(menuSave);

        // setup the frame and add components
        frame = new JFrame();

        frame.setJMenuBar(menuBar);
        frame.add(west,   BorderLayout.WEST);
        frame.add(center, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        frame.pack();

        // give the focus to the center panel
        center.requestFocusInWindow();

        frame.setVisible(true);
    }


    // draw picture (gif, jpg, or png) centered on (x, y)
    public void picture(int x, int y, String filename) {
        ImageIcon icon = new ImageIcon(filename);
        Image image = icon.getImage();
        offscreen.drawImage(image, x, y, null);
        show();
    }


    // display the drawing canvas on the screen
    public void show() {
        onscreen.drawImage(offscreenImage, 0, 0, null);
        frame.repaint();
    }



   /*************************************************************************
    *  Event callbacks
    *************************************************************************/

    // for buttons and menus
    public void actionPerformed(ActionEvent e) {
        Object cmd = e.getActionCommand();
        if      (cmd.equals(" Save...   ")) System.out.println("File -> Save");
        else if (cmd.equals("button 1"))    System.out.println("Button 1 pressed");
        else if (cmd.equals("button 2"))    System.out.println("Button 2 pressed");
        else if (cmd.equals("button 3"))    System.out.println("Button 3 pressed");
        else if (cmd.equals("button 4"))    System.out.println("Button 4 pressed");
        else                                System.out.println("Unknown action");

        // don't hog the keyboard focus
        center.requestFocusInWindow();
    }

    // for the mouse
    public void mousePressed(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse pressed at " + x + ", " + y);
        offscreen.setColor(Color.BLUE);
        offscreen.fillOval(x-3, y-3, 6, 6);
        show();
    }

    public void mouseClicked (MouseEvent e) { }
    public void mouseReleased(MouseEvent e) { }
    public void mouseEntered (MouseEvent e) { }
    public void mouseExited  (MouseEvent e) { }
    public void mouseDragged (MouseEvent e) { }
    public void mouseMoved   (MouseEvent e) { }


    // for the keyboard
    public void keyPressed (KeyEvent e) { }
    public void keyReleased(KeyEvent e) { }

    public void keyTyped(KeyEvent e) {
        System.out.println("Key = '" + e.getKeyChar() + "'");
    }

    // test client
    public static void main(String[] args) {
        GUI gui = new GUI(800, 471);
        gui.picture(0, 0, "map.png");
        gui.show();
    }

}

enter image description here enter image description here

Comments

0

If you like lesser code lines in your code try below code:

Inside your buttons actionPerformed:

  private void yourButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               

            final JPopupMenu yourMenu = new JPopupMenu("Settings");
            menu.add("Name");
            menu.add("Id");
            menu.add(new Button()); // can even add buttons and other components as well.
            menu.show(yourButton, yourButton.getWidth()/2, yourButton.getHeight()/2);                                         
}     

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.