package test;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

/**

*/

public class ContextualMenuClearsTextSelection
{
    public ContextualMenuClearsTextSelection()
    {
        String instructions =
          "Click in the blank part of the text field to clear the selection\n"
          + "Triple click over the word to select the text\n"
          + "Control-click over the word to open a popup menu\n"
          + "The text selection should remain, but it is cleared";

        JFrame frame = new JFrame("Test");

        JTextField tf = new JTextField("Word");
        frame.add(tf);
        createPopup(tf);

        JTextArea ta = new JTextArea(instructions);
        frame.add(ta, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }

    private void createPopup(JTextField f)
    {
        JPopupMenu m = new JPopupMenu();
        m.add(new JMenuItem("Apple"));
        m.add(new JMenuItem("Pear"));
        m.add(new JMenuItem("Grape"));

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

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

            private void showPopupMenu(MouseEvent e)
            {
                m.show((Component) e.getSource(), e.getX(), e.getY());
            }
        };

        f.addMouseListener(a);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(ContextualMenuClearsTextSelection::new);
    }
}
