Tuesday, April 26, 2011

How to create pop up menu in java


When you're working on a worksheet, such as Word or Notepad and then you do right-click popup menu will appear that contains facilities Copy, Paste, and so forth.
By using the API PopupMenu, you can create your own menu. Popup menu is defined by an event trigger that is able to control the program, and refined through MouseEvent method which is used to detect the mouse.


Below are examples of program code:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class PopUpMenu extends JPanel implements ActionListener{
PopupMenu popup;

public PopUpMenu(){
MenuItem mi;
popup=new PopupMenu("Edit");
mi=new MenuItem("Cut");
mi.addActionListener(this);
popup.add(mi);

mi=new MenuItem("Copy");
mi.addActionListener(this);
popup.add(mi);
add(popup);
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
resize(200,200);
}
public void processMouseEvent(MouseEvent e){
if(e.isPopupTrigger()){
popup.show(e.getComponent(),e.getX(),e.getY());
}
super.processMouseEvent(e);
}
public void actionPerformed(ActionEvent e){
String command=e.getActionCommand();
if (command.equals("Cut")){
JOptionPane.showMessageDialog(null,"CUT");
}
}
public static void main(String args[]){
JFrame frame=new JFrame();

frame.getContentPane().add(new PopUpMenu(),BorderLayout.CENTER);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
frame.setSize(300,300);
}

}


Save with filename: PopUpMenu.java

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Blogger Templates