Popup menu merupakan menu yang akan ditampilkan saat kita melakukan klik kanan di window. Program berikut ini merupakan contoh program membuat popup menu di Java. Class yang digunakan adalah JPopupMenu.
Tampilanya
Berikut ini source code programnya:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupMenuTest extends JFrame {
private JRadioButtonMenuItem items[];
private final Color colorValues[] = {Color.BLUE, Color.YELLOW, Color.RED};
private JPopupMenu popMenu;
public PopupMenuTest() {
super ("Menu Popup");
ItemHandler handler = new ItemHandler();
String colorNames[] = {"Biru", "Kuning", "Merah"};
ButtonGroup colorGroup = new ButtonGroup();
popMenu = new JPopupMenu();
items = new JRadioButtonMenuItem [colorValues.length];
for (int i = 0; i < items.length; i++) {
items[i] = new JRadioButtonMenuItem (colorNames[i]);
popMenu.add (items[i]);
colorGroup.add (items[i]);
items[i].addActionListener(handler);
}
getContentPane().setBackground(Color.WHITE);
addMouseListener(
new MouseAdapter() {
public void mousePressed (MouseEvent e) {
showPopupMenu (e);
}
public void mouseReleased (MouseEvent e) {
showPopupMenu (e);
}
private void showPopupMenu(MouseEvent e) {
if (e.isPopupTrigger())
popMenu.show(e.getComponent(), e.getX(), e.getY());
}
} //end of anonymous class
); //end of addMouseListener
setSize (400,300);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
PopupMenuTest test = new PopupMenuTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ItemHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
//
for (int i = 0; i < items.length; i++) {
if (e.getSource() == items[i]) {
getContentPane().setBackground (colorValues[i]);
return;
}
}
}
}
}
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment