Selasa, 04 Oktober 2011

Contoh Program Java

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:
01import java.awt.*;
02import java.awt.event.*;
03import javax.swing.*;
04 
05public class PopupMenuTest extends JFrame {
06    private JRadioButtonMenuItem items[];
07    private final Color colorValues[] = {Color.BLUE, Color.YELLOW, Color.RED};
08    private JPopupMenu popMenu;
09 
10    public PopupMenuTest() {
11        super ("Menu Popup");
12 
13        ItemHandler handler = new ItemHandler();
14        String colorNames[] = {"Biru", "Kuning", "Merah"};
15 
16        ButtonGroup colorGroup = new ButtonGroup();
17        popMenu = new JPopupMenu();
18        items = new JRadioButtonMenuItem [colorValues.length];
19 
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);
25           }
26 
27        getContentPane().setBackground(Color.WHITE);
28 
29        addMouseListener(
30            new MouseAdapter() {
31                public void mousePressed (MouseEvent e) {
32                    showPopupMenu (e);
33                }
34 
35                public void mouseReleased (MouseEvent e) {
36                    showPopupMenu (e);
37                }
38 
39                private void showPopupMenu(MouseEvent e) {
40                    if (e.isPopupTrigger())
41                        popMenu.show(e.getComponent(), e.getX(), e.getY());
42                }
43            } //end of anonymous class
44        ); //end of addMouseListener
45 
46        setSize (400,300);
47        setLocationRelativeTo (null);
48        setVisible (true);
49    }
50 
51    public static void main (String args[]) {
52        JFrame.setDefaultLookAndFeelDecorated(true);
53        PopupMenuTest test = new PopupMenuTest();
54        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
55    }  
56 
57    private class ItemHandler implements ActionListener {
58        public void actionPerformed (ActionEvent e) {
59            //
60            for (int i = 0; i < items.length; i++) {
61                if (e.getSource() == items[i]) {
62                    getContentPane().setBackground (colorValues[i]);
63                    return;
64                }
65            }
66        }
67    }
68}

0 komentar:

Posting Komentar