Wednesday, January 8, 2014

Java example of using JPopupMenu

JPopupMenu
JPopupMenu

package javamenu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMenu extends JFrame {

    JLabel jLabel;
    JPopupMenu jPopupMenu;

    private void prepareUI() {

        jLabel = new JLabel("Label", JLabel.RIGHT);
        getContentPane().add(jLabel);

        jPopupMenu = new JPopupMenu();
        JMenuItem jMenuItem_A = new JMenuItem("Menu Item A");
        JMenuItem jMenuItem_B = new JMenuItem("Menu Item B");
        JMenuItem jMenuItem_C = new JMenuItem("Menu Item C");
        jPopupMenu.add(jMenuItem_A);
        jPopupMenu.add(jMenuItem_B);
        jPopupMenu.add(jMenuItem_C);
        jMenuItem_A.addActionListener(menuActionListener);
        jMenuItem_B.addActionListener(menuActionListener);
        jMenuItem_C.addActionListener(menuActionListener);

        addMouseListener(myMouseAdapter);
    }

    MouseAdapter myMouseAdapter = new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
        
        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }

    };
    
    ActionListener menuActionListener = new ActionListener(){
 
        @Override
        public void actionPerformed(ActionEvent e) {
            jLabel.setText(e.getActionCommand());
        }
         
    };

    private static void createAndShowGUI() {
        JavaMenu myFrame = new JavaMenu();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(400, 300);
        myFrame.prepareUI();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

}

No comments:

Post a Comment