Selasa, 13 Maret 2012

Event Handling

  • Event Handling 
    Event Handling merupakan konsep penanganan suatu action yang terjadi. Jadi suatu program akan berjalan saat sesuatu terjadi, misalnya saat tombol diklik, saat combo box dipilih dan sebagainya. Java memiliki beberapa jenis Event Handling, salah satunya adalah class ActionListener yang menangani aksi terhadap tombol.

  • Contoh Program



    import java.awt.*;
         
        import java.awt.event.*;
         
        import javax.swing.*;
         
        public class ClickMe3 extends JFrame {
         
            private JButton tombol, btnExit;
         
            public ClickMe3() {
         
                super ("Event Handling");
         
                Container container = getContentPane();
         
                container.setLayout(new FlowLayout());
         
                ClickListener cl = new ClickListener ();
         
                tombol = new JButton ("Click Me!");
         
                tombol.addActionListener(cl);
         
                container.add(tombol);
         
                btnExit = new JButton ("Exit");
         
                btnExit.addActionListener(cl);
         
                container.add(btnExit);
         
                setSize (200,100);
         
                setVisible (true);
         
            }
         
            public static void main (String arg[]) {
         
                ClickMe3 test = new ClickMe3();
         
                test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
            }
         
            //inner class
         
            private class ClickListener implements ActionListener {
         
            public void actionPerformed (ActionEvent e) {
     
                if (e.getSource() == tombol) {
     
                    JOptionPane.showMessageDialog(null, "You click me again, guys !!!");
     
                } else if (e.getSource() == btnExit){
     
                    if ( JOptionPane.showConfirmDialog(null, "Apakah Anda yakin akan keluar ?","Konfirmasi",
     
                            JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
     
                            System.exit(0);
     
                        }
     
                }
     
            }
     
        }
     
    }
  • Argument Class

  • Inner Class
    Inner Class adalah suatu Class yang didefinisikan di dalam Class lain. Dengan kata lain, Inner Class adalah anggota (member) dari Class lain, sama halnya seperti variable dan method. Hal ini mengakibatkan instance dari Inner Class dapat mengakses /berbagi dengan instance dari outer Class-nya. Instance dari Inner Class dapat mengakses semua member dari outer Class-nya, bahkan yang private.
    Contoh :

    class MyOuter{

    private int x = 7;

    class MyInner {

    public void seeOuter(){

    System.out.println(“Outer x is ” + x);

    }

    }

    }

    source : http://contohprogram.info/

Java GUI

  • Pengertian GUI
    Adalah citra grafis yang ditampilkan di layar komputer yang memungkinkan untuk mengakses aplikasi software dengan memakai menu dropdown, dialog box, radio button, check box, panel, tabs, toolbar, icon shortcuts dan tool lain.

  • Pengertian Java GUI
    Adalah pemrograman dengan bahasa Java yang dibuat menggunakan aplikasi yang berbasiskan GUI.
    Di Java terdapat beberapa macam pemrograman berbasis GUI(Graphical User Interface).
     
  • Swing - SUN Microsystem -> Oracle
    Swing Java adalah salah satu pemrograman berbasis GUI(Graphical User Interface) di Java.
    • Contoh :

      public class SwingForm extends javax.swing.JFrame {
       
          /** Creates new form SwingForm */
          public SwingForm() {
              initComponents();
          }
       
          @SuppressWarnings("unchecked")
          // <editor-fold defaultstate="collapsed" desc="Generated Code">
          private void initComponents() {
              .....
          }// </editor-fold>
       
          private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
              // TODO add your handling code here:
          }                                        
       
          private void resetLaf() {
              SwingUtilities.updateComponentTreeUI(this);
          }
       
          private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
              try {
                  UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                  resetLaf();
              } catch (ClassNotFoundException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (InstantiationException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (IllegalAccessException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (UnsupportedLookAndFeelException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
       
          private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
              try {
                  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                  resetLaf();
              } catch (ClassNotFoundException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (InstantiationException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (IllegalAccessException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (UnsupportedLookAndFeelException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
       
          private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
              try {
                  UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                  resetLaf();
              } catch (ClassNotFoundException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (InstantiationException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (IllegalAccessException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (UnsupportedLookAndFeelException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
       
          private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {
              try {
                  UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                  resetLaf();
              } catch (ClassNotFoundException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (InstantiationException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (IllegalAccessException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              } catch (UnsupportedLookAndFeelException ex) {
                  Logger.getLogger(SwingForm.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
       
          .....
          .....
      }


  • AWT (Abstract Window Toolkit)
    Adalah GUI toolkit pertama pada bahasa pemrograman Java, sayang-nya AWT ini sangat-sangat kekurangan komponen yang biasa digunakan untuk membangun sebuah aplikasi desktop secara lengkap. Terlepas dari kurang-nya komponen GUI yang terdapat pada AWT, aplikasi yang dibangun menggunakan AWT akan tampak seperti aplikasi native. Maksudnya yaitu, jika aplikasi yang dibangun menggunakan AWT ini dijalankan pada Sistem Operasi Windows. Maka aplikasi ini akan terlihat seperti aplikasi Windows pada umum-nya, dan begitu juga jika dijalankan pada Sistem Operasi Mac ataupun GNU/Linux.
    • Contoh :
      AWTWindows
      Tampilan Aplikasi Berbasis AWT Di Ms Windows
      AWTExample
      Tampilan Aplikasi Berbasis AWT Di GNU/Linux
      Sedangkan source-code yang digunakan pada tampilan form diatas adalah seperti dibawah ini :


      public class AwtFrame extends java.awt.Frame {
          private java.awt.CheckboxGroup checkBoxGroup;
       
          public AwtFrame() {
              checkBoxGroup = new java.awt.CheckboxGroup();
       
              initComponents();
          }
       
          private void initComponents() {
              panel1 = new java.awt.Panel();
              label1 = new java.awt.Label();
              txtKdBarang = new java.awt.TextField();
              label2 = new java.awt.Label();
              txtNmBarang = new java.awt.TextField();
              label3 = new java.awt.Label();
              checkBoxEceran = new java.awt.Checkbox();
              checkBoxPack = new java.awt.Checkbox();
              txtArea = new java.awt.TextArea();
              button1 = new java.awt.Button();
              button2 = new java.awt.Button();
              menuBar1 = new java.awt.MenuBar();
              menu1 = new java.awt.Menu();
              menuItem1 = new java.awt.MenuItem();
              menu2 = new java.awt.Menu();
       
              setMinimumSize(new java.awt.Dimension(500, 300));
              setTitle("AWT Form Example");
              addWindowListener(new java.awt.event.WindowAdapter() {
                  public void windowClosing(java.awt.event.WindowEvent evt) {
                      exitForm(evt);
                  }
              });
       
              label1.setText("Kode Barang");
              label2.setText("Nama Barang");
              label3.setText("Kategori");
       
              checkBoxEceran.setCheckboxGroup(checkBoxGroup);
              checkBoxEceran.setLabel("Eceran");
              checkBoxEceran.setState(true);
       
              checkBoxPack.setCheckboxGroup(checkBoxGroup);
              checkBoxPack.setLabel("Pack");
       
              button1.setLabel("Tambah");
              button1.addActionListener(new java.awt.event.ActionListener() {
                  public void actionPerformed(java.awt.event.ActionEvent evt) {
                      button1ActionPerformed(evt);
                  }
              });
       
              button2.setLabel("Clear");
              button2.addActionListener(new java.awt.event.ActionListener() {
                  public void actionPerformed(java.awt.event.ActionEvent evt) {
                      button2ActionPerformed(evt);
                  }
              });
       
              add(panel1, java.awt.BorderLayout.CENTER);
              menu1.setLabel("File");
              menuItem1.setLabel("Exit");
              menuItem1.addActionListener(new java.awt.event.ActionListener() {
                  public void actionPerformed(java.awt.event.ActionEvent evt) {
                      menuItem1ActionPerformed(evt);
                  }
              });
              menu1.add(menuItem1);
              menuBar1.add(menu1);
              menu2.setLabel("Edit");
              menuBar1.add(menu2);
              setMenuBar(menuBar1);
              pack();
          }// </editor-fold>
       
          /** Exit the Application */
          private void exitForm(java.awt.event.WindowEvent evt) {                          
              System.exit(0);
          }                         
       
          private void menuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
              exitForm(new java.awt.event.WindowEvent(this, WIDTH));
          }
       
          private void clearField() {
              txtKdBarang.setText("");
              txtNmBarang.setText("");
          }
       
          private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
              txtArea.append("\nKode Barang     = " + txtKdBarang.getText());
              txtArea.append("\nNama Barang    = " + txtNmBarang.getText());
              txtArea.append("\nKategori Barang = " + checkBoxGroup.getSelectedCheckbox().getLabel());
              clearField();
              txtKdBarang.requestFocusInWindow();
          }
       
          private void button2ActionPerformed(java.awt.event.ActionEvent evt) {
              clearField();
              txtArea.setText("");
          }
       
          // Variables declaration - do not modify
          private java.awt.Button button1;
          private java.awt.Button button2;
          private java.awt.Checkbox checkBoxEceran;
          private java.awt.Checkbox checkBoxPack;
          private java.awt.Label label1;
          private java.awt.Label label2;
          private java.awt.Label label3;
          private java.awt.Menu menu1;
          private java.awt.Menu menu2;
          private java.awt.MenuBar menuBar1;
          private java.awt.MenuItem menuItem1;
          private java.awt.Panel panel1;
          private java.awt.TextArea txtArea;
          private java.awt.TextField txtKdBarang;
          private java.awt.TextField txtNmBarang;
      }


  • SWT (Standard Widget Toolkit)
    Sebagai GUI (Graphical User Interface) di dalam Eclipse Platform. SWT merupakan produk IBM, begitu juga Eclipse sendiri dan sampai saat ini sangat diterima di kalangan pengembang Java.
    • Contoh :
      /** This source code taken from :
       * http://www.eclipse.org/articles/article.php?file=Article-Understanding-Layouts/index.html
       * 
       * @author Martinus Ady H <mrt.itnewbies@gmail.com>
       */
      public class Main {
       
          Text dogName;
          Combo dogBreed;
          Canvas dogPhoto;
          Image dogImage;
          List categories;
          Text ownerName;
          Text ownerPhone;
       
          public static void main(String[] args) {
              Display display = new Display();
              Shell shell = new Main().createShell(display);
              shell.open();
              while (!shell.isDisposed()) {
                  if (!display.readAndDispatch()) {
                      display.sleep();
                  }
              }
          }
       
          public Shell createShell(final Display display) {
              final Shell shell = new Shell(display);
              shell.setText("SWT Form Example");
              GridLayout gridLayout = new GridLayout();
              gridLayout.numColumns = 3;
              shell.setLayout(gridLayout);
       
              new Label(shell, SWT.NONE).setText("Dog's Name:");
       
              dogName = new Text(shell, SWT.SINGLE | SWT.BORDER);
              GridData gridData = new GridData(GridData.FILL, GridData.CENTER, true, false);
              gridData.horizontalSpan = 2;
              dogName.setLayoutData(gridData);
       
              new Label(shell, SWT.NONE).setText("Breed:");
       
              dogBreed = new Combo(shell, SWT.NONE);
              dogBreed.setItems(new String[]{"Collie", "Pitbull", "Poodle",
                          "Scottie", "Black Lab"});
              dogBreed.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
       
              Label label = new Label(shell, SWT.NONE);
              label.setText("Categories");
              label.setLayoutData(new GridData(GridData.CENTER, GridData.CENTER, true, false));
       
              new Label(shell, SWT.NONE).setText("Photo:");
              dogPhoto = new Canvas(shell, SWT.BORDER);
              gridData = new GridData(GridData.FILL, GridData.FILL, true, true);
              gridData.widthHint = 80;
              gridData.heightHint = 80;
              gridData.verticalSpan = 3;
              dogPhoto.setLayoutData(gridData);
              dogPhoto.addPaintListener(new PaintListener() {
                  public void paintControl(final PaintEvent event) {
                      if (dogImage != null) {
                          event.gc.drawImage(dogImage, 0, 0);
                      }
                  }
              });
       
              categories = new List(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
              categories.setItems(new String[]{"Best of Breed", "Prettiest Female",
                          "Handsomest Male", "Best Dressed", "Fluffiest Ears",
                          "Most Colors", "Best Performer", "Loudest Bark",
                          "Best Behaved", "Prettiest Eyes", "Most Hair", "Longest Tail",
                          "Cutest Trick"});
              gridData = new GridData(GridData.FILL, GridData.FILL, true, true);
              gridData.verticalSpan = 4;
              int listHeight = categories.getItemHeight() * 12;
              Rectangle trim = categories.computeTrim(0, 0, 0, listHeight);
              gridData.heightHint = trim.height;
              categories.setLayoutData(gridData);
       
              Button browse = new Button(shell, SWT.PUSH);
              browse.setText("Browse...");
              gridData = new GridData(GridData.FILL, GridData.CENTER, true, false);
              gridData.horizontalIndent = 5;
              browse.setLayoutData(gridData);
              browse.addSelectionListener(new SelectionAdapter() {
                  public void widgetSelected(SelectionEvent event) {
                      String fileName = new FileDialog(shell).open();
                      if (fileName != null) {
                          dogImage = new Image(display, fileName);
                      }
                  }
              });
       
              Button delete = new Button(shell, SWT.PUSH);
              delete.setText("Delete");
              gridData = new GridData(GridData.FILL, GridData.BEGINNING, true, false);
              gridData.horizontalIndent = 5;
              delete.setLayoutData(gridData);
              delete.addSelectionListener(new SelectionAdapter() {
                  public void widgetSelected(SelectionEvent event) {
                      if (dogImage != null) {
                          dogImage.dispose();
                          dogImage = null;
                          dogPhoto.redraw();
                      }
                  }
              });
       
              Group ownerInfo = new Group(shell, SWT.NONE);
              ownerInfo.setText("Owner Info");
              gridLayout = new GridLayout();
              gridLayout.numColumns = 2;
              ownerInfo.setLayout(gridLayout);
              gridData = new GridData(GridData.FILL, GridData.CENTER, true, false);
              gridData.horizontalSpan = 2;
              ownerInfo.setLayoutData(gridData);
       
              new Label(ownerInfo, SWT.NONE).setText("Name:");
              ownerName = new Text(ownerInfo, SWT.SINGLE | SWT.BORDER);
              ownerName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
       
              new Label(ownerInfo, SWT.NONE).setText("Phone:");
              ownerPhone = new Text(ownerInfo, SWT.SINGLE | SWT.BORDER);
              ownerPhone.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
       
              Button enter = new Button(shell, SWT.PUSH);
              enter.setText("Enter");
              gridData = new GridData(GridData.END, GridData.CENTER, false, false);
              gridData.horizontalSpan = 3;
              enter.setLayoutData(gridData);
              enter.addSelectionListener(new SelectionAdapter() {
                  public void widgetSelected(SelectionEvent event) {
                      System.out.println("\nDog Name: " + dogName.getText());
                      System.out.println("Dog Breed: " + dogBreed.getText());
                      System.out.println("Owner Name: " + ownerName.getText());
                      System.out.println("Owner Phone: " + ownerPhone.getText());
                      System.out.println("Categories:");
                      String cats[] = categories.getSelection();
                      for (int i = 0; i > cats.length; i++) {
                          System.out.println("\t" + cats[i]);
                      }
                  }
              });
       
              shell.addDisposeListener(new DisposeListener() {
                  public void widgetDisposed(DisposeEvent arg0) {
                      if (dogImage != null) {
                          dogImage.dispose();
                          dogImage = null;
                      }
                  }
              });
       
              shell.pack();
       
              return shell;
          }
      }
    source :
    http://blog.fastncheap.com/
    http://contohprogram.info/
    http://martinusadyh.web.id/