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.
Berikut ini tampilan programnya:
erikut ini source code programnya:
02 | import java.awt.event.*; |
05 | public class PopupMenuTest extends JFrame { |
06 | private JRadioButtonMenuItem items[]; |
07 | private final Color colorValues[] = {Color.BLUE, Color.YELLOW, Color.RED}; |
08 | private JPopupMenu popMenu; |
10 | public PopupMenuTest() { |
13 | ItemHandler handler = new ItemHandler(); |
14 | String colorNames[] = { "Biru" , "Kuning" , "Merah" }; |
16 | ButtonGroup colorGroup = new ButtonGroup(); |
17 | popMenu = new JPopupMenu(); |
18 | items = new JRadioButtonMenuItem [colorValues.length]; |
20 | for ( int i = 0 ; i < items.length; i++) { |
21 | items[i] = new JRadioButtonMenuItem (colorNames[i]); |
22 | popMenu.add (items[i]); |
23 | colorGroup.add (items[i]); |
24 | items[i].addActionListener(handler); |
27 | getContentPane().setBackground(Color.WHITE); |
31 | public void mousePressed (MouseEvent e) { |
35 | public void mouseReleased (MouseEvent e) { |
39 | private void showPopupMenu(MouseEvent e) { |
40 | if (e.isPopupTrigger()) |
41 | popMenu.show(e.getComponent(), e.getX(), e.getY()); |
47 | setLocationRelativeTo ( null ); |
51 | public static void main (String args[]) { |
52 | JFrame.setDefaultLookAndFeelDecorated( true ); |
53 | PopupMenuTest test = new PopupMenuTest(); |
54 | test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
57 | private class ItemHandler implements ActionListener { |
58 | public void actionPerformed (ActionEvent e) { |
60 | for ( int i = 0 ; i < items.length; i++) { |
61 | if (e.getSource() == items[i]) { |
62 | getContentPane().setBackground (colorValues[i]); |
0 komentar:
Posting Komentar