Magazine
 

Tips & Tricks

 

To add it to the Applet you need to use the Swing component set. In the program code given below, we have used MouseEvent.isPopupTrigger() method to trigger
the MouseEvent that pops up the menu. The example below shows the triggering of a popup menu and its activation through a command button.

Code of Program: PopupMenuDemo.java

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class PopupMenuDemo extends Applet{
Button b;
TextField msg;
PopupAppMenu m;
public PopupMenuDemo(){
setSize(200, 200);
b = new Button(“Pop-up Menu”);
add(b, BorderLayout.NORTH);
msg = new TextField();
msg.setEditable(false);
add(msg, BorderLayout.SOUTH);
m = new PopupAppMenu(this);
add(m);
b.addActionListener(new
ActionListener(){
public void actionPerformed(ActionEvent e){
m.show(b, 20, 20);
}
});
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
if (e.isPopupTrigger())
m.show(e.getComponent(), e.getX(),
e.getY());
}
public void mouseReleased(MouseEvent e){
if (e.isPopupTrigger())
m.show(e.getComponent(), e.getX(),
e.getY());
}
});
}
public static void main(String[] args){
popupMenuDemo app = new
PopupMenuDemo();
app.setVisible(true);

 

}
class PopupAppMenu extends PopupMenu
implements ActionListener{
PopupMenuDemo ref;
public PopupAppMenu(PopupMenuDemo ref){
super(“File”);
this.ref = ref;
MenuItem mi;
add(mi = new MenuItem(“Copy”));
mi.addActionListener(this);
add(mi = new MenuItem(“Open”));
mi.addActionListener(this);
add(mi = new MenuItem(“Cut”));
mi.addActionListener(this);
add(mi = new MenuItem(“Paste”));
mi.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String item = e.getActionCommand();
ref.msg.setText(“Option Selected: “ + item);
}
}

PopupMenuDemo.html

<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN=”CENTER”
CODE=”PopupMenuDemo.class”
WIDTH=”800" HEIGHT=”500"></APPLET>
</BODY>
</HTML>

Run the program:

C:\newprgrm>javac PopupMenuDemo.java
C:\newprgrm>appletviewer
PopupMenuDemo.html

Jan 2007 | Java Jazz Up | 97
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 ,

83, 84 , 85 , 86, 87 , 88, 89 , 90 , 91 , 92 , 93 , 94 , 95 , 96 , 97 , 98 , 99 , 100 , 101 , 102 , 103, 104 , 105 ,

106, 107,

Download PDF