/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import javax.swing.* ; 

2. import java.awt.* ; 

3. import java.awt.event.*; 

4.  

5. public class PopupSw 

6.     extends JApplet 

7.     implements MouseListener, ActionListener 

8.

9.   JPopupMenu pmnu ; 

10.   JMenuItem setcol ; 

11.   JMenuItem del ; 

12.  

13.   JList lst ; 

14.   JLabel lbl ; 

15.   JTextField tf ; 

16.   Component cmp = null

17.   int x = 0, y = 0

18.  

19.   JComponent cp ; 

20.  

21.   private void 

22.   pop ( MouseEvent ev ) 

23.   { 

24.     if ( ev.isPopupTrigger ()  ) 

25.     { 

26.       cmp = ev.getComponent () ; 

27.       x = ev.getX () ; 

28.       y = ev.getY () ; 

29.       pmnu.show ( cmp, x, y ) ; 

30.     } 

31.   } 

32.   public void mousePressed( MouseEvent ev ) 

33.   { 

34.     pop ( ev ) ; 

35.   } 

36.   public void mouseReleased ( MouseEvent ev ) 

37.   { 

38.     pop ( ev ) ; 

39.   } 

40.   public void 

41.   actionPerformed( ActionEvent ev ) 

42.   { 

43.     Object src = ev.getSource() ; 

44.  

45.     if ( src == setcol  &&  cmp != null

46.     { 

47.       cmp.setBackground ( Color.yellow ) ; 

48.       return

49.     } 

50.     if ( src == del  &&  cmp != null

51.     { 

52.       cp.remove ( cmp ) ; 

53.       cmp = null

54.       cp.revalidate(); 

55.       cp.repaint(); 

56.       return

57.     } 

58.   } 

59.   public 

60.   PopupSw( ) 

61.   { 

62.     pmnu = new JPopupMenu () ; 

63.  

64.     setcol = new JMenuItem ( "Set color" ) ; 

65.     del = new JMenuItem ( "Delete component" ) ; 

66.  

67.     pmnu.add ( setcol ) ; 

68.     pmnu.add ( del ) ; 

69.  

70.     String[] data = {"Rachmaninoff", "Skriabin"}; 

71.     lst = new JList( data ); 

72.     lbl = new JLabel ( "Just a Label" ) ; 

73.     tf= new JTextField ( "Taxed veal" ) ; 

74.   } 

75.  

76.   public void 

77.   init() 

78.   { 

79.     setcol.addActionListener ( this ) ; 

80.     del.addActionListener ( this ) ; 

81.  

82.     cp = (JComponent)getContentPane(); 

83.     cp.setLayout( new FlowLayout() ); 

84.     cp.add ( lst ) ; 

85.     lbl.setOpaque(true); 

86.     cp.add ( lbl ) ; 

87.     cp.add ( tf ) ; 

88.  

89.     lst.addMouseListener ( this ) ; 

90.     lbl.addMouseListener ( this ) ; 

91.     tf.addMouseListener ( this ) ; 

92.   } 

93.  

94.   public void mouseClicked(MouseEvent ev) {} 

95.   public void mouseEntered(MouseEvent ev) {} 

96.   public void mouseExited(MouseEvent ev) {} 

97.