コード例 #1
0
  /** Creates new form. */
  public PopupMenuTest() {
    initComponents();

    ActionListener a =
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            System.out.println(evt);
          }
        };

    JPopupMenu pm = new JPopupMenu();
    JMenu m;
    JMenuItem mi;
    JCheckBoxMenuItem cbmi;
    JRadioButtonMenuItem crmi;
    mi = new JMenuItem("Menu Item 1");
    mi.addActionListener(a);
    pm.add(mi);
    mi = new JMenuItem("Menu Item 2");
    mi.addActionListener(a);
    pm.add(mi);
    mi = new JMenuItem("Menu Item 3");
    mi.addActionListener(a);
    pm.add(mi);

    m = new JMenu("Menu 1");
    mi = new JMenuItem("Menu Item 1.1");
    mi.addActionListener(a);
    m.add(mi);
    mi = new JMenuItem("Menu Item 1.2");
    mi.addActionListener(a);
    m.add(mi);
    pm.add(m);

    pm.addSeparator();
    cbmi = new JCheckBoxMenuItem("Checkbox Menu Item");
    pm.add(cbmi);

    pm.addSeparator();
    ButtonGroup group = new ButtonGroup();
    crmi = new JRadioButtonMenuItem("Radio Menu Item 1");
    crmi.setSelected(true);
    group.add(crmi);
    pm.add(crmi);

    crmi = new JRadioButtonMenuItem("Radio Menu Item 2");
    group.add(crmi);
    pm.add(crmi);
    popupMenu = pm;

    /*
    //setComponentPopupMenu(pm);
    //jLabel1.setComponentPopupMenu(pm);
    JButton button = new JButton("Hi");
    // button.setComponentPopupMenu(pm);
    button.setInheritsPopupMenu(true);
    add(button, BorderLayout.SOUTH);
     */
    MouseAdapter popper1 =
        new MouseAdapter() {
          public void mousePressed(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
              showPopupMenu(evt);
            }
          }

          public void mouseReleased(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
              showPopupMenu(evt);
            }
          }

          protected void showPopupMenu(MouseEvent evt) {
            popupMenu.show((Component) evt.getSource(), evt.getX(), evt.getY());
          }
        };

    popupLabel1.addMouseListener(popper1);
    popupField.addMouseListener(popper1);

    MouseAdapter popper2 =
        new MouseAdapter() {
          public void mousePressed(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
              showPopupMenu(evt);
            }
          }

          public void mouseReleased(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
              showPopupMenu(evt);
            }
          }

          protected void showPopupMenu(MouseEvent evt) {
            Dimension ps = popupMenu.getPreferredSize();
            popupMenu.show(popupLabel2, evt.getX() - ps.width / 2, evt.getY() - ps.height / 2);
          }
        };

    popupLabel2.addMouseListener(popper2);
  }
コード例 #2
0
 @Override
 public void show(Component c, int x, int y) {
   int[] l = table.getSelectedRows();
   deleteAction.setEnabled(l.length > 0);
   super.show(c, x, y);
 }