Add action listener to popup menuitem in Java
Description
The following code shows how to add action listener to popup menuitem.
Example
/*w w w .j a va2 s . c o m*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
class PopupActionListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Selected: " + actionEvent.getActionCommand());
}
}
public class Main {
public static void main(final String args[]) {
JFrame frame = new JFrame("PopupSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPopupMenu popupMenu = new JPopupMenu("Title");
ActionListener actionListener = new PopupActionListener();
// Copy
JMenuItem copyMenuItem = new JMenuItem("Copy");
copyMenuItem.addActionListener(actionListener);
popupMenu.add(copyMenuItem);
JButton label = new JButton("java2s.com");
frame.add(label);
label.setComponentPopupMenu(popupMenu);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »