Graphical User Interface Programming

Document Sample
Graphical User Interface Programming Powered By Docstoc
					Graphical User Interface
    Programming
                         GUI
   Graphical User Interface
       event driven programming
   Java GUI programming
       AWT (Abstract Window Toolkit)
       Swing
        Event driven programming
   Uses a signal-and-response approach
       Events and event handlers
       Asynchronous
   Event = object that act as a signal to another
    object
   Listener = event receiver
   One event might have zero or more listeners.
   Listeners can receive events from different
    objects.
      Event driven programming
   One event might have zero or more listeners.

                             Listerner A


       Button
         X                   Listerner B




                             Listerner C
      Event driven programming
   Listeners can receive events from different
    objects.
        Button
          X


                              Listerner A
        Button
          Y



        Button
          Z
                              Listerner B
                Typical events
   User moves the mouse.
   User clicks the mouse button.
   User clicks the mouse button in a button in a
    window.
   User presses a key on the keyboard.
   Timer event occurs.
     Typical programming and event
          driven programming
   Up to now your programs consisted of lists of
    statements executed in order.

   In event-drive programming, you create
    objects that can fire events, and you create
    listener objects that react to the events.
       You don’t know the order ahead of time.
       Typically, your code never directly calls the
        listener methods.
 Windows

via Swing’s JFrame
   Creating a window in Swing
import javax.swing.JFrame;

…
JFrame f = new JFrame( “My Simple Frame” );
f.setSize( 300, 200 ); //w, h
f.setDefaultCloseOperation(
      JFrame.DO_NOTHING_ON_CLOSE );
…
f.setVisible( true );
      Adding a button to a window
               (JFrame)
import javax.swing.JButton;
…
//create the button
JButton b1 = new JButton( “Click to end program” );
//associate the listener with this button (next slide)
MyButtonListener listener = new MyButtonListener();
b1.addActionListener( listener );

f.add( b1 );      //add the button to our frame
              Our button listener
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MyButtonListener implements ActionListener {

    public void actionPerformed ( ActionEvent e ) {
        System.exit( 0 );
    }

}
               (Typical) Steps
1.   Create the frame.
2.   Create the button.
3.   Create the action listener for the button.
4.   Add the action listener to the button (register
     the action listener with the button).
5.   Add the button to the frame.
6.   Show the frame.
                      Pixel
   Smallest unit of space on which your screen
    can write.
   Contraction for … what?
           Useful JFrame methods
   public JFrame ( )
   public JFrame ( String title )
   public void setDefaultCloseOperation ( int operation )
       JFrame.DO_NOTHING_ON_CLOSE
       JFrame.HIDE_ON_CLOSE
       JFrame.DISPOSE_ON_CLOSE
       JFrame.EXIT_ON_CLOSE
       Note: The close-window-button is part of the JFrame (not
        a JButton)
   public void setSize ( int width, int height )
     More useful JFrame methods
   public void setTitle ( String title )
   public void add ( Component componentAdded )
   public void setLayout ( LayoutManager manager )
   public void setJMenuBar ( JMenuBar menubar )
   public void dispose ( )
   public void setVisible ( boolean makeVisible )
  Buttons

via Swing’s JButton
             Buttons (JButton)
   Different kinds of components require
    different kinds of listener classes to handle the
    events they fire.
   A button fires events known as action events,
    which are handled by listeners know as action
    listeners.
Back to creating a window in Swing
import javax.swing.JFrame;

…
JFrame f = new JFrame( “My Simple Frame” );
f.setSize( 300, 200 ); //w, h This is not a very
f.setDefaultCloseOperation( OO approach!
      JFrame.DO_NOTHING_ON_CLOSE );
…
f.setVisible( true );
    A more OO approach to creating a
           window in Swing
import javax.swing.JFrame;

public MyFrame extends JFrame {
   public static final int sWidth = 300;
   public static final int sHeight = 200;
   MyFrame ( ) {
        super( “My More OO Simple Frame” );
        setSize( sWidth, sHeight );
        setDefaultCloseOperation(
                  JFrame.DO_NOTHING_ON_CLOSE );
        …
        setVisible( true );
    }
    …
}
           JLabel – a line of text
   Simply a line of text appearing in a window.
    import javax.swing.JLabel;
    …
    JLabel label = new JLabel( “hello there.” );
    add( label );
            Programming in Color
import java.awt.Color;
…
Color.BLACK
 Also

       Color.BLUE, Color.CYAN, Color.DARK_GRAY, …
       Or you can specify/create your own colors by specifying
        the argb or rgb values in the Color ctor.
   Use getContentPane().setBackground( Color.BLUE );
    to change the background color of your JFrame.
            Programming in color
   Colors are represented by their RGB value.
       R=red
       G=green
       B=blue
       When R is the largest value, the color has more red
        than the other components. What happens when
        r=g=b?
       Sometimes ARGB is used where A=alpha
        (opacity)
Layout Managers
         Controlling the placement of
        components in a container (our
                   frame)
   So far, we simply add components to a container and accept
    whatever default layout is presented.
   Layout manager – describes how the components are arranged.
   Java provides many layout managers.
       Border (in book)
       Box (not in book)
       Card (not in book)
       Flow (in book)
       Grid (in book)
       Grid bag (not in book)
       Group (not in book)
       Spring (not in book)
                  BorderLayout
    Places the components in five areas:
    1.   North
    2.   South
    3.   East
    4.   West
    5.   Center
    You specify the area in the add method.
        add( new JLabel(“me”), BorderLayout.NORTH );
          Using the BorderLayout
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MyFrame extends JFrame {
   public MyFrame ( ) {
         super( “My frame w/ border layout.” );
         setSize( 300, 200 );
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         setLayout( new BorderLayout() );
         add( new JLabel( “first” ), BorderLayout.NORTH );
         add( new JLabel( “second” ), BorderLayout.SOUTH );
         …
         setVisible( true );
   }
}
                  FlowLayout
   Simplest.

   Arranges components one after another from
    left to right and top to bottom in the order in
    which one adds them.
              Using the FlowLayout
import   java.awt.FlowLayout;
import   javax.swing.JButton;
import   javax.swing.JFrame;
import   javax.swing.JLabel;

public class MyFrame extends JFrame {
   public MyFrame ( ) {
         super( “My frame w/ flow layout.” );
         setSize( 300, 200 );
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         setLayout( new FlowLayout() );
         add( new JLabel( “first” ) );
         add( new JButton( “second” ) );
         …
         setVisible( true );
   }
}
                  GridLayout
   Arranges components
    on a 2D grid of given
    size (i.e., rows and
    cols specified via the
    GridLayout ctor).

   Each entry in the grid
    will be stretched to
    the same size.
                        GridLayout
   Placement rules are more complicated.
       Say we have a 2 x 3 (2 rows x 3 cols):
            new GridLayout( 2, 3 )
       If we subsequently add six things, they will appear
        in a 2x3 grid of equally sized elements.




       What happens if we add more or less?
                     GridLayout
   Placement rules are
    more complicated.
       Say we have a 2 x 3 (2
        rows x 3 cols).

       Adding 7 or 8 items
        causes a col to be added.

       Adding fewer than 6
        items causes a col(s) to    X
        be deleted.
                    GridLayout
   Placement rules are more complicated.
       Say we have a 2 x 3 (2 rows x 3 cols).

       To only honor the number of rows, specify a 0 for
        the cols.

       To honor only the number of cols, specify a 0 for
        the rows.
              Using the GridLayout
import   java.awt.GridLayout;
import   javax.swing.JButton;
import   javax.swing.JFrame;
import   javax.swing.JLabel;

public class MyFrame extends JFrame {
   public MyFrame ( ) {
         super( “My frame w/ flow layout.” );
         setSize( 300, 200 );
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         setLayout( new GridLayout(0,1) ); //always a single col
         add( new JLabel( “first” ) );
         add( new JButton( “second” ) );
         …
         setVisible( true );
   }
}
    Summary of Layout Managers
   FlowLayout
       Displays components from left to right in the order
        in which they are added to the container.
   BorderLayout
       Displays the components in five areas: N, S, E, W,
        and Center. You specify the area in the add
        method.
   GridLayout
       Lays out components in a grid with each
        component stretched to fill its box in the grid.
       Additional Layout Managers
   Box (not in book)
   Card (not in book)
   Tabbed pane (not in book; not strictly a layout
    manager)
   Grid bag (not in book)
   Group (not in book)
   Spring (not in book)
                  BoxLayout




“either stacks its components on top of each other or
  places them in a row - your choice” from
  http://java.sun.com/docs/books/tutorial/uiswing/layou
  t/box.html
                 CardLayout
   Typically used to switch between different
    panels.
   Poor man’s version of tabbed pane.
                                   choice here
                                            causes change here
               JTabbedPane
   Not strictly a layout manager.
   Typically preferred over CardLayout.
                   GridBagLayout
“… if you want to code by hand and do not want to use GroupLayout, then
  GridBagLayout is recommended as the next most flexible and powerful
  layout manager” from
  http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
                      GroupLayout
“… if you want to code by hand and do not want to use GroupLayout, then
  GridBagLayout is recommended as the next most flexible and powerful
  layout manager” from
  http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html

Intended to be used by GUI builder.
                SpringLayout

   Intended to be used by GUI builder.
        JPanel

a general purpose window-like
           container
                  Panels (JPanel)
   General purpose, window-like container
   Groups objects
   Components may be added to them (including
    other panels)
       hierarchical
   Layout manager can be associated w/ a panel
   Can be added to a JFrame
                      Example JPanels
                                            JPanel w/ a top-to-bottom
                                            BoxLayout



                                            subclass of JPanel w/ a
                                            left-to-right BoxLayout




subclass of JPanel w/ a
top-to-bottom BoxLayout

                JPanel w/ a top-to-bottom
                BoxLayout
                           JPanel Example
import   javax.swing.JFrame;              public static void main ( String[] args ) {
import   javax.swing.JPanel;                  PanelDemo gui = new PanelDemo( );
import   java.awt.BorderLayout;               gui.setVisible( true );
import   java.awt.GridLayout;               }
import   java.awt.FlowLayout;
import   java.awt.Color;                    public void actionPerformed ( ActionEvent e ) {
import   javax.swing.JButton;                 String buttonString = e.getActionCommand();
import   java.awt.event.ActionListener;
import   java.awt.event.ActionEvent;            if (buttonString.equals("Red"))
                                                    redPanel.setBackground( Color.RED );
public class PanelDemo extends JFrame           else if (buttonString.equals("White"))
   implements ActionListener                       whitePanel.setBackground(Color.WHITE);
{                                               else if (buttonString.equals("Blue"))
  public static final int WIDTH = 300;             bluePanel.setBackground( Color.BLUE );
  public static final int HEIGHT = 200;         else
                                                   System.out.println( "Unexpected error.“ );
  private JPanel redPanel = new JPanel();   }
  private JPanel whitePanel = new JPanel();
  private JPanel bluePanel = new JPanel();
public PanelDemo ( ) {
    super( "Panel Demonstration“ );
    setSize( WIDTH, HEIGHT );
                             JPanel Example
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setLayout( new BorderLayout( ) );           JPanel buttonPanel = new JPanel( );
                                                 buttonPanel.setBackground( Color.LIGHT_GRAY );
    JPanel biggerPanel = new JPanel( );          buttonPanel.setLayout( new FlowLayout( ) );
   biggerPanel.setLayout( new GridLayout(1, 3) );
                                                            JButton redButton = new JButton( "Red“ );
   redPanel.setBackground( Color.LIGHT_GRAY );              redButton.setBackground( Color.RED );
   biggerPanel.add( redPanel );                             redButton.addActionListener( this );
                                                            buttonPanel.add( redButton );
   whitePanel.setBackground( Color.LIGHT_GRAY );
   biggerPanel.add( whitePanel );                JButton whiteButton = new JButton( "White“ );
                                                 whiteButton.setBackground( Color.WHITE );
   bluePanel.setBackground( Color.LIGHT_GRAY ); whiteButton.addActionListener( this );
   biggerPanel.add( bluePanel );                 buttonPanel.add( whiteButton );

   add( biggerPanel, BorderLayout.CENTER );                 JButton blueButton = new JButton( "Blue“ );
                                                            blueButton.setBackground( Color.BLUE );
                                                            blueButton.addActionListener( this );
                                                            buttonPanel.add( blueButton );

                                                            add( buttonPanel, BorderLayout.SOUTH );
                                                        }

                                                    }
                      JPanel Example
   PanelDemo (JFrame w/ BorderLayout)
       biggerPanel (w/ GridLayout of 1 row & 3 cols)
            added at center
            redPanel
            whitePanel
            bluePanel
       buttonPanel (w/ FlowLayout)
            added at south
            redButton
            whiteButton
            blueButton
           The Container class
   Can have components added to it
   JFrame & JPanel are descendents of Container
   Container class = any descendent of Container
   Component = any descendent of JComponent
   You may add any component to any container
   JComponent is derived from Container so you
    may add a JComponent to a JComponent
The MVC Pattern

MVC = Model+View+Controller
    Model-View-Controller (from
          wikipedia.org)
   Model
       The domain-specific representation of the information on
        which the application operates. Domain logic adds meaning
        to raw data (e.g., calculating whether today is the user's
        birthday, or the totals, taxes, and shipping charges for
        shopping cart items).

       Many applications use a persistent storage mechanism
        (such as a database) to store data. MVC does not
        specifically mention the data access layer because it is
        understood to be underneath or encapsulated by the Model.
    Model-View-Controller (from
          wikipedia.org)
   View
       Renders the model into a form suitable for interaction,
        typically a user interface element.

       Multiple views can exist for a single model for different
        purposes.
    Model-View-Controller (from
          wikipedia.org)
   Controller
       Processes and responds to events, typically user actions,
        and may invoke changes on the model.
              Basic MVC
                 Model
                 data1
                 data2
                   .             manipulate
notify
                   .
                   .




    View                  Controller
         …                   …
   update()                  …
         …
     Model-View-Controller (from
           wikipedia.org)
   Though MVC comes in different flavors, control flow generally works as
    follows:
     1.   The user interacts with the user interface in some way (e.g., presses a
          button).
     2.   A controller handles the input event from the user interface, often via a
          registered handler or callback.
     3.   The controller accesses the model, possibly updating it in a way appropriate
          to the user's action (e.g., controller updates user's shopping cart).
     4.   A view uses the model (indirectly) to generate an appropriate user interface
          (e.g., the view produces a screen listing the shopping cart contents). The
          view gets its own data from the model. The model has no direct knowledge
          of the view.
     5.   The user interface waits for further user interactions, which begins the cycle
          anew.
   By decoupling models and views, MVC helps to reduce the complexity in
    architectural design, and to increase flexibility and reuse.
Model-View-Controller (from
      wikipedia.org)
                   A simple diagram depicting
                   the relationship between the
                   Model, View, and Controller.

                   Note: the solid lines indicate
                   a direct association, and the
                   dashed lines indicate an
                   indirect association (e.g.,
                   observer pattern).
             Observer pattern
“The observer pattern is a software design
  pattern in which an object, called the subject,
  maintains a list of its dependents, called
  observers, and notifies them automatically of
  any state changes, usually by calling one of
  their methods. It is mainly used to implement
  distributed event handling systems.”


from http://en.wikipedia.org/wiki/Observer_pattern
Model (data)
       ConnectFour
             |                                               Main
             |
             V
    MyConnectFour




View (output)                                    Controller (input events)

          MyView                                         MyController




A diagram depicting the relationship between the Model, View, and Controller
for the ConnectFour game. Note: the solid lines indicate a direct association,
and the dashed lines indicate an indirect association (e.g., observer pattern).
                            Note
   Some designers combine/simply the M-V-C to
    D-V where…
       D is the document, data, or model,
       V is the View, and
       the controller is typically part of the view.
Menus and buttons
Menu bars, menus, and menu items
   JMenuBar, JMenu, and JMenuItem
       import:
            javax.swing.JMenuBar
                 ex. the menu bar in an app
            javax.swing.JMenu
                 ex. File
                 ex. Edit
                 ex. Help
            javax.swing.JMenuItem
                 ex. Open in the File menu
                 ex. Cut in the Edit menu
       implement ActionListener for events
            Example


                      menu bar




                  menu


menu item
    Example: creating a menu bar
…
public class MenuDemo extends JFrame implements ActionListener {
   …
   public MenuDemo ( ) {
         …
         JMenu colorMenu = new JMenu( “Add colors” );

        JMenuItem greenChoice = new JMenuItem( “Green” );
        greenChoice.addActionListener( this );
        colorMenu.add( greenChoice );
        …
        JMenuBar bar = new JMenuBar();
        bar.add( colorMenu );
        setJMenuBar( bar );
    }
    …
}
          Handling menu events
   When we create a button or menu item, we
    specify a string.
   By default, that string becomes the action
    command for that button.
   The action command is provided to the
    actionPerformed method.
   The action command can be changed via
    setActionCommand (there is also a
    getActionCommand method as well).
   Example: handle menu events
…
public class MenuDemo extends JFrame implements ActionListener {
   …
   public void actionPerformed ( ActionEvent e ) {
         String action = e.getActionCommand();
         if (action.equals( “Green” ))
                   greenPanel.setBackground( Color.GREEN );
         else if (action.equals( “White” )
                   whitePanel.setBackground( Color.WHITE );
         …
         else
                   System.out.println( “Unexpected action” );
   }
   …
}
Advanced topic: sub/nested menus




                        submenu
                  submenus
   Similarly to adding menu items to a menu, we
    may also add menus to menus. (Note that
    JMenuItem is a superclass of JMenu below.)
Text fields and text areas
            Text field (JTextField)
   A field that allows the user to enter a single line of
    text.
   Ex.
    JTextField name = new JTextField( 30 );
    …
    String inputString = name.getText();
    …
    name.setText( “fred” );

    JTextField f2 = new JTextField( “ethel”, 30 ); //default value

       30 is the minimum number of visible characters (more may
        be entered)
          Text area (JTextArea)
   Same as text field except it allows multiple lines.
   Ex.
    JTextArea theText = new JTextArea( 5, 20 );

    JTextArea t2 = new JTextArea( “hello\nthere”, 5, 20 );

    5 is the minimum number of visible lines.
    20 is the minimum number of visible characters.
       Some useful JTextComponent
                 methods
   public String getText()

   public boolean isEditable()

   public void setBackground ( Color theColor )

   public void setEditable ( boolean argument )

   public void setText ( String text )

				
DOCUMENT INFO