Minggu, 23 September 2012

Window Event di Java

 

Penanganan Event Dalam Windos


Contoh bagaimana penanganan event di dalam window. Event akan aktif saat window diubah ukurannnya, diclose, aktif, dan sebagainya. Listener yang digunakan dalam contoh program ini adalah WindowListener, WindowFocusListener dan WindowStateListener.
Berikut ini tampilannya:
contoh-program-window-event-java

Berikut ini program lengkapnya:
001/*
002 * WindowEventDemo.java is a 1.4 example that requires
003 * no other files.
004 */
005
006import javax.swing.*;
007import java.awt.*;
008import java.awt.event.*;
009
010public class WindowEventDemo extends JPanel
011                             implements WindowListener,
012                                        WindowFocusListener,
013                                        WindowStateListener {
014    final static String newline = "\n";
015    final static String space = "    ";
016    static JFrame frame;
017    JTextArea display;
018
019    public WindowEventDemo() {
020        super(new BorderLayout());
021        display = new JTextArea();
022        display.setEditable(false);
023        JScrollPane scrollPane = new JScrollPane(display);
024        scrollPane.setPreferredSize(new Dimension(500, 450));
025        add(scrollPane, BorderLayout.CENTER);
026
027        frame.addWindowListener(this);
028        frame.addWindowFocusListener(this);
029        frame.addWindowStateListener(this);
030
031        checkWM();
032    }
033
034    //Some window managers don't support all window states.
035    //For example, dtwm doesn't support true maximization,
036    //but mimics it by resizing the window to be the size
037    //of the screen.  In this case the window does not fire
038    //the MAXIMIZED_ constants on the window's state listener.
039    //Microsoft Windows supports MAXIMIZED_BOTH, but not
040    //MAXIMIZED_VERT or MAXIMIZED_HORIZ.
041    public void checkWM() {
042        Toolkit tk = frame.getToolkit();
043        if (!(tk.isFrameStateSupported(Frame.ICONIFIED))) {
044            displayMessage(
045               "Your window manager doesn't support ICONIFIED.");
046        }
047        if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_VERT))) {
048            displayMessage(
049               "Your window manager doesn't support MAXIMIZED_VERT.");
050        }
051        if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))) {
052            displayMessage(
053               "Your window manager doesn't support MAXIMIZED_HORIZ.");
054        }
055        if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_BOTH))) {
056            displayMessage(
057               "Your window manager doesn't support MAXIMIZED_BOTH.");
058        } else {
059            displayMessage(
060               "Your window manager supports MAXIMIZED_BOTH.");
061        }
062    }
063
064    public void windowClosing(WindowEvent e) {
065        displayMessage("WindowListener method called: windowClosing.");
066
067        //A pause so user can see the message before
068        //the window actually closes.
069        ActionListener task = new ActionListener() {
070            boolean alreadyDisposed = false;
071            public void actionPerformed(ActionEvent e) {
072                if (!alreadyDisposed) {
073                    alreadyDisposed = true;
074                    frame.dispose();
075                } else { //make sure the program exits
076                    System.exit(0);
077                }
078            }
079        };
080        Timer timer = new Timer(500, task); //fire every half second
081        timer.setInitialDelay(2000);        //first delay 2 seconds
082        timer.start();
083    }
084
085    public void windowClosed(WindowEvent e) {
086        //This will only be seen on standard output.
087        displayMessage("WindowListener method called: windowClosed.");
088    }
089
090    public void windowOpened(WindowEvent e) {
091        displayMessage("WindowListener method called: windowOpened.");
092    }
093
094    public void windowIconified(WindowEvent e) {
095        displayMessage("WindowListener method called: windowIconified.");
096    }
097
098    public void windowDeiconified(WindowEvent e) {
099        displayMessage("WindowListener method called: windowDeiconified.");
100    }
101
102    public void windowActivated(WindowEvent e) {
103        displayMessage("WindowListener method called: windowActivated.");
104    }
105
106    public void windowDeactivated(WindowEvent e) {
107        displayMessage("WindowListener method called: windowDeactivated.");
108    }
109
110    public void windowGainedFocus(WindowEvent e) {
111        displayMessage("WindowFocusListener method called: windowGainedFocus.");
112    }
113
114    public void windowLostFocus(WindowEvent e) {
115        displayMessage("WindowFocusListener method called: windowLostFocus.");
116    }
117
118    public void windowStateChanged(WindowEvent e) {
119        displayStateMessage(
120          "WindowStateListener method called: windowStateChanged.", e);
121    }
122
123    void displayMessage(String msg) {
124        display.append(msg + newline);
125        System.out.println(msg);
126    }
127
128    void displayStateMessage(String prefix, WindowEvent e) {
129        int state = e.getNewState();
130        int oldState = e.getOldState();
131        String msg = prefix
132                   + newline + space
133                   + "New state: "
134                   + convertStateToString(state)
135                   + newline + space
136                   + "Old state: "
137                   + convertStateToString(oldState);
138        display.append(msg + newline);
139        System.out.println(msg);
140    }
141
142    String convertStateToString(int state) {
143        if (state == Frame.NORMAL) {
144            return "NORMAL";
145        }
146        if ((state & Frame.ICONIFIED) != 0) {
147            return "ICONIFIED";
148        }
149        //MAXIMIZED_BOTH is a concatenation of two bits, so
150        //we need to test for an exact match.
151        if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
152            return "MAXIMIZED_BOTH";
153        }
154        if ((state & Frame.MAXIMIZED_VERT) != 0) {
155            return "MAXIMIZED_VERT";
156        }
157        if ((state & Frame.MAXIMIZED_HORIZ) != 0) {
158            return "MAXIMIZED_HORIZ";
159        }
160        return "UNKNOWN";
161    }
162
163    /**
164     * Create the GUI and show it.  For thread safety,
165     * this method should be invoked from the
166     * event-dispatching thread.
167     */
168    private static void createAndShowGUI() {
169        //Make sure we have nice window decorations.
170        JFrame.setDefaultLookAndFeelDecorated(true);
171
172        //Create and set up the window.
173        frame = new JFrame("WindowEventDemo");
174        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
175
176        //Create and set up the content pane.
177        JComponent newContentPane = new WindowEventDemo();
178        newContentPane.setOpaque(true); //content panes must be opaque
179        frame.setContentPane(newContentPane);
180
181        //Display the window.
182        frame.pack();
183        frame.setVisible(true);
184    }
185
186    public static void main(String[] args) {
187        //Schedule a job for the event-dispatching thread:
188        //creating and showing this application's GUI.
189        javax.swing.SwingUtilities.invokeLater(new Runnable() {
190            public void run() {
191                createAndShowGUI();
192            }
193        });
194    }
195}

Jumat, 21 September 2012

Massage Dialog Java

Tampilan Program

contoh-program-message-dialog-java


Berikut ini contoh programnya:

001import java.awt.*;
002 
003import java.awt.event.*;
004 
005import javax.swing.*;
006 
007public class MessageDialog extends JFrame {
008 
009    private JButton tombol, btn2, btn3, btn4, btn5;
010 
011    public MessageDialog() {
012 
013        super ("Event Handling");
014 
015        Container container = getContentPane();
016 
017        container.setLayout(new FlowLayout());
018 
019        tombol = new JButton ("Message Dialog");
020 
021        tombol.addActionListener(
022 
023            new ActionListener() {
024 
025                public void actionPerformed (ActionEvent e) {
026 
027                    JOptionPane.showMessageDialog (null,"Contoh Message Dialog");
028 
029                }
030 
031            }
032 
033        );
034 
035        container.add(tombol);
036 
037        btn2 = new JButton ("Warning Message");
038 
039        btn2.addActionListener(
040 
041            new ActionListener() {
042 
043                public void actionPerformed (ActionEvent e) {
044 
045                    JOptionPane.showConfirmDialog(null, "Contoh Warning Message","Peringatan",
046 
047                        JOptionPane.CLOSED_OPTION, JOptionPane.WARNING_MESSAGE);
048 
049                }
050 
051            }
052 
053        );
054 
055        container.add(btn2);
056 
057        btn3 = new JButton ("Question Message");
058 
059        btn3.addActionListener(
060 
061            new ActionListener() {
062 
063                public void actionPerformed (ActionEvent e) {
064 
065                    JOptionPane.showConfirmDialog(null, "Contoh Question Message","Pertanyaan",
066 
067                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
068 
069                }
070 
071            }
072 
073        );
074 
075        container.add(btn3);
076 
077        btn4 = new JButton ("Information Message");
078 
079        btn4.addActionListener(
080 
081            new ActionListener() {
082 
083                public void actionPerformed (ActionEvent e) {
084 
085                    JOptionPane.showConfirmDialog(null, "Contoh Information Message","Informasi",
086 
087                        JOptionPane.NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
088 
089                }
090 
091            }
092 
093        );
094 
095        container.add(btn4);
096 
097        btn5 = new JButton ("Input Dialog");
098 
099        btn5.addActionListener(
100 
101            new ActionListener() {
102 
103                public void actionPerformed (ActionEvent e) {
104 
105                    String a = JOptionPane.showInputDialog("Input Nama : ");
106 
107                    JOptionPane.showMessageDialog(null, a);
108 
109                }
110 
111            }
112 
113        );
114 
115        container.add(btn5);
116 
117        setSize (200,300);
118 
119        setLocationRelativeTo(null);
120 
121        setVisible (true);
122 
123    }
124 
125    public static void main (String arg[]) {
126 
127        MessageDialog test = new MessageDialog();
128 
129        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
130 
131    }
132 
133}

Menggambar Poligon Java


Tampilan Program

menggambar-poligon-java


Dan berikut ini contoh program lengkapnya:


01import java.awt.*;
02 
03import javax.swing.*;
04 
05public class DrawPolygons extends JFrame {
06 
07    public DrawPolygons() {
08        super ("Menggambar Polygon");
09        setSize (400,300);
10        show();
11    }
12 
13    public void paint(Graphics g) {
14        super.paint (g);
15 
16        int xValues[] = {20,40,50,30,20,15};
17        int yValues[] = {50,50,60,80,80,60};
18        Polygon poly1 = new Polygon (xValues, yValues, 6); //(arrX, arrY, jumTitik)
19 
20        g.drawPolygon (poly1);
21        int xValues2[] = {70,90,100,80,70,65,60};
22        int yValues2[] = {100,100,110,110,130,110,90};
23        g.drawPolyline (xValues2, yValues2, 7);    
24 
25        int xValues3[] = {120,140,150,190};
26        int yValues3[] = {40,70,80,60};
27        g.fillPolygon (xValues3, yValues3, 4);
28 
29        Polygon poly2 = new Polygon();
30        poly2.addPoint (220,100);
31        poly2.addPoint (175,150);
32        poly2.addPoint (270,150);
33        g.fillPolygon (poly2);
34    }
35 
36    public static void main (String args[]) {
37 
38        DrawPolygons test = new DrawPolygons();
39        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
40    }
41 
42}

Program Key Event Java

Tampilan Program

contoh-program-key-event-java


Dan berikut ini program lengkapnya
01import java.awt.*;
02import java.awt.event.*;
03import javax.swing.*;
04 
05public class KeyEventTest extends JFrame implements KeyListener {
06    private String baris1="", baris2="", baris3="";
07    private JTextArea textArea;
08 
09    public KeyEventTest() {
10        super ("Mencoba Key Event");
11 
12        textArea = new JTextArea (10,15);
13        textArea.setText("Tekan sembarang tombol di keyboard...");
14        textArea.setEnabled(false);
15        textArea.setDisabledTextColor(Color.BLACK);
16        getContentPane().add(textArea);
17 
18        addKeyListener (this);
19 
20        setSize (300,150);
21        setLocationRelativeTo(null);
22        setVisible(true);
23    }
24 
25    public void keyPressed (KeyEvent e) {
26        baris1 = "Tombol yang ditekan : " + e.getKeyText(e.getKeyCode());
27        setLines2and3 (e);
28    }
29 
30    public void keyReleased (KeyEvent e) {
31        baris1 = "Tombol yang dilepas : " + e.getKeyText(e.getKeyCode());
32        setLines2and3 (e);
33    }
34 
35    public void keyTyped (KeyEvent e) {
36        baris1 = "Tombol yang ditulis : " + e.getKeyChar();
37        setLines2and3 (e);
38    }
39 
40    private void setLines2and3 (KeyEvent e) {
41        baris2 = "This key is "+ (e.isActionKey() ? "" : "not ") + "an action key";
42        String temp = e.getKeyModifiersText(e.getModifiers());
43        baris3 = "Modifier key pressed : " + (temp.equals("") ? "none" : temp);
44        textArea.setText(baris1 + "\n" + baris2 + "\n" + baris3 + "\n");
45    }
46 
47    public static void main (String args[]) {
48            KeyEventTest test = new KeyEventTest();
49            test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
50        }
51}