JPanel: setComponentPopupMenu(JPopupMenu popup) : JPanel « javax.swing « Java by API






JPanel: setComponentPopupMenu(JPopupMenu popup)

  

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

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Main implements ActionListener {
  JTextArea textArea = new JTextArea();

  public Main() {
    final JPopupMenu contextMenu = new JPopupMenu("Edit");
    contextMenu.add(makeMenuItem("Save"));
    contextMenu.add(makeMenuItem("Save As"));
    contextMenu.add(makeMenuItem("Close"));

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    frame.add(panel);
    panel.setComponentPopupMenu(contextMenu);

    textArea.setInheritsPopupMenu(true);
    panel.add(BorderLayout.CENTER, textArea);

    JTextField textField = new JTextField();
    textField.setInheritsPopupMenu(true);
    panel.add(BorderLayout.SOUTH, textField);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 200);
    frame.setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
    textArea.append(e.getActionCommand() + "\n");
  }

  private JMenuItem makeMenuItem(String label) {
    JMenuItem item = new JMenuItem(label);
    item.addActionListener(this);
    return item;
  }

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

   
    
  








Related examples in the same category

1.JPanel: addAncestorListener(AncestorListener lis)
2.JPanel: addContainerListener(ContainerListener l)
3.JPanel: addMouseListener(MouseListener mous)
4.JPanel: addMouseMotionListener(MouseMotionListener lis)
5.JPanel: addKeyListener(KeyListener l)
6.JPanel: getFocusTraversalKeys(int id)
7.JPanel: isFocusCycleRoot()
8.JPanel: paintComponent(Graphics g)
9.JPanel: repaint()
10.JPanel: setBackground(Color c)
11.JPanel: setBorder(Border border)
12.JPanel: setFocusCycleRoot(boolean value)
13.JPanel: setFocusTraversalPolicyProvider(boolean value)
14.JPanel: setLayout(null)
15.JPanel: setOpaque(boolean isOpaque)
16.JPanel: setPreferredSize(Dimension preferredSize)
17.JPanel: setToolTipText(String htmlString)
18.extends JPanel