The source program is as follows:
Import javax. swing .*;
Import java. awt .*;
Import java. awt. event .*;
Import javawork. swing .*;
Public class Popup extends JApplet
{
Private JPopupMenu popup = new JPopupMenu ();
Private JTextField t = new JTextField (10 );
Public void init ()
{
Container cp = getContentPane ();
Cp. setLayout (new FlowLayout ());
Cp. add (t );
ActionListener al = new ActionListener ()
{
Public void actionreceivmed (ActionEvent e)
{
T. setText (JMenuItem) e. getSource (). getText ());
}
};
JMenuItem m = new JMenuItem ("Hither ");
M. addActionListener (al );
Popup. add (m );
M = new JMenuItem ("yon ");
M. addActionListener (al );
Popup. add (m );
M = new JMenuItem ("Afar ");
M. addActionListener (al );
Popup. add (m );
// Void addSeparator ()
// Appends a new separator at the end of the menu.
Popup. addSeparator ();
M = new JMenuItem ("Stay here ");
M. addActionListener (al );
Popup. add (m );
PopupListener pl = new PopupListener ();
AddMouseListener (pl );
T. addMouseListener (pl ); //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// ///////////////////////////
}
Class PopupListener extends MouseAdapter
{
Public void mousePressed (MouseEvent e)
{
MaybeShowPopup (e );
}
Public void mouseReleased (MouseEvent e)
{
MaybeShowPopup (e );
}
Private void maybeShowPopup (MouseEvent e)
{
If (e. isPopupTrigger ())
Popup. show (JApplet) e. getComponent (). getContentPane (), e. getX (), e. getY ());
}
}
Public static void main (String [] args)
{
Console. run (new Popup (), 300,200 );
}
}
Opinion:
T. addMouseListener (pl ); //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// ///////////////////////////
This line is not necessary. After adding this line, right-click the text field and you will see many exceptions in the console,
If the row is removed, none of these exceptions occur, but the pop-up menu will not appear when you click the text field!