JPopupMenu: add(JMenuItem menuItem) : JPopupMenu « javax.swing « Java by API






JPopupMenu: add(JMenuItem menuItem)

 
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;

public class MainClass {

  public static void main(final String args[]) {
    JFrame frame = new JFrame("Popup Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    final JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);

    final JPopupMenu popup = new JPopupMenu();
    JMenuItem menuItem1 = new JMenuItem("Option 1");
    popup.add(menuItem1);

    JMenuItem menuItem2 = new JMenuItem("Option 2");
    popup.add(menuItem2);

    
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        popup.show(textField, 10,10);
      }
    };
    
    KeyStroke keystroke =
      KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
    textField.registerKeyboardAction(actionListener, keystroke,
      JComponent.WHEN_FOCUSED);

    frame.setSize(250, 150);
    frame.setVisible(true);
  }

}

           
         
  








Related examples in the same category

1.JPopupMenu: addPopupMenuListener(PopupMenuListener lis)
2.JPopupMenu: addSeparator()
3.JPopupMenu: setDefaultLightWeightPopupEnabled(boolean aFlag)
4.JPopupMenu: setLightWeightPopupEnabled(boolean aFlag)
5.JPopupMenu: show(Component invoker, int x, int y)