Programming
language 2
Java GUI – part 1
                         Loredana STANCIU
                    loredana.stanciu@upt.ro
                                Room B616
What is a user interface
 That part of a program that interacts with the user of the
  program:
     simple command-line interfaces
     point-and-click graphical user interfaces
 A common set of tools for graphical user interface design
  that work on a variety of platforms
 A user interface toolkit called the Abstract Windowing
  Toolkit, or the AWT
Components and containers
 A graphical user interface is built of graphical elements
  called components: buttons, scrollbars, and text fields
 Components do not stand alone, but rather are found
  within containers.
 Contain and control the layout of components
Components and containers
 Components must fit completely within the
  container
 Creates a tree of elements, starting with the
  container at the root of the tree and expanding out
  to the leaves
GUI – Graphical User interface
Types of components
Types of components
 Button
 Button()
   Creates a button
 Button(String label)
   Creates a labeled button
 void addActionListener(ActionListener l)
   Adds the specified action listener to receive
    action events from this button.
 Button
 String getLabel()
   Gets the label of the current button.
 void setLabel(String label)
   Sets the button's label to be the specified string.
Button — example
 You can create a button by creating an
  instance of the Button class:
Button buttonOne = new Button();
Button buttonOne = new Button("This is a
  button");
 You can add a button to a frame by using the
  add() method:
aFrame.add(buttonOne);
CheckBox
 A graphical component that can be in either an
  "on" (true) or "off" (false) state.
 setLayout(new GridLayout(3, 1));
 add(new Checkbox("one", null, true));
 add(new Checkbox("two"));
 add(new Checkbox("three"));
CheckBox
 Checkbox()
    Creates a check box with no label
 Checkbox(String label)
    Creates a check box with the specified label
 Checkbox(String label, boolean state)
   Creates a check box with the specified label
    and sets the specified state
 Checkbox(String label,
  CheckboxGroup group, boolean state,)
    Creates a check box with the label, set to the
     state, and in the check box group
CheckBox
 void addItemListener (ItemListener l)
   Adds the specified item listener to receive
    item events from this check box.
 String getLabel()
   Gets the label of this check box.
 Boolean getState()
   Determines whether this check box is in the
   "on" or "off" state
CheckBox
 void setCheckboxGroup(CheckboxGroup g)
    Sets this check box's group to be the
     specified check box group.
 void setLabel(String label)
    Sets this check box's label to be the string
     argument.
 void setState(boolean state)
 Sets the state of this check box to the specified
  state.
CheckboxGroup
 Used to group together a set of Checkbox
  buttons.
 Exactly one check box button in a
  CheckboxGroup can be in the "on" state at any
  given time
 Pushing any button sets its state to "on" and
  forces any other button that is in the "on" state
  into the "off" state
CheckboxGroup — Example
 setLayout(new GridLayout(3, 1));
 CheckboxGroup cbg = new CheckboxGroup();
 add(new Checkbox("one", cbg, true));
  add(new Checkbox("two", cbg, false));
  add(new Checkbox("three", cbg, false));
Chioce
 A pop-up menu of choices. The current choice is
  displayed as the title of the menu.
 Choice ColorChooser = new Choice();
  ColorChooser.add("Green");
  ColorChooser.add("Red");
  ColorChooser.add("Blue");
Chioce
 Choice()
   Creates a new choice menu.
 void add(String item)
   Adds an item to this Choice menu.
 void addItemListener(ItemListener l)
   Adds the specified item listener to receive
    item events from this Choice menu.
 String getItem(int Index)
   Gets the string at the specified index in this
    Choice menu.
Chioce
 int getItemCount()
   Returns the number of items in this Choice
    menu.
 int getSelectedIndex()
   Returns the index of the currently selected
    item.
 String getSelectedItem()
   Gets a representation of the current choice
    as a string.
Chioce
 void insert(String item, int index)
   Inserts the item into this choice at the
    specified position.
 void remove(int position)
   Removes an item from the choice menu at
    the specified position.
 void remove(String item)
   Removes the first occurrence of item from the
    Choice menu.
Chioce
 void removeAll()
   Removes all items from the choice menu.
 void select(int position)
   Sets the selected item in this Choice menu to
    be the item at the specified position.
 void select(String str)
   Sets the selected item in this Choice menu to
   be the item whose name is equal to the
   specified string.
Label
 A component for placing text in a container.
 Displays a single line of read-only text.
 setLayout(new
  FlowLayout(FlowLayout.CENTER, 10, 10));
 add(new Label("Hi There!"));
 add(new Label("Another Label"));
Label
 Label(String text);
   Creates a new instance of Label
 String getText();
   Returns a label’s text
 void setText(String text);
   Sets a label’s text to the specified text
Scrollbar
 Provides a convenient means for allowing a user to
  select from a range of values.
 redSlider=new
  Scrollbar(Scrollbar.VERTICAL, 0, 1, 0,
  255);
 add(redSlider);
 ranger = new
  Scrollbar(Scrollbar.HORIZONTAL, 0, 60, 0,
  300);
 add(ranger);
Scrollbar
 Scrollbar()
   Constructs a new vertical scroll bar.
 Scrollbar(int orientation)
   Constructs a new scroll bar with the specified
    orientation.
Scrollbar
 Scrollbar(int orientation, int value,
  int visible, int minimum, int maximum)
   Constructs a new scroll bar with the specified
    orientation, initial value, visible amount, and
    minimum and maximum values.
 void addAdjunstmentListener(Adjust
  mentListener l)
   Adds the specified adjustment listener to receive
    instances of AdjustmentEvent from this scroll
    bar.
TextField
 A text component that allows for the editing of a
  single line of text.
 TextField tf1, tf2, tf3, tf4;
 tf1 = new TextField();
 tf2 = new TextField("", 20);
 tf3 = new TextField("Hello!");
 tf4 = new TextField("Hello", 30);
TextField
 TextField()
   Creates a new instance of TextField
 TextField(String text)
   Creates a new instance of TextField with
    the specified text
 void setColumns(int columns)
   Sets the number of columns in a textbox
 void setText(String text)
   Sets a textfield text to the specified text
List
 A scrolling list of text items. The list can be set up
  so that the user can choose either one item or
  multiple items.
 List lst = new List(4, false);
  lst.add("Mercury"); lst.add("Venus");
  lst.add("Earth"); lst.add("JavaSoft");
  lst.add("Mars"); lst.add("Jupiter");
  lst.add("Saturn"); lst.add("Uranus");
  lst.add("Neptune"); lst.add("Pluto");
List
 List()
   Creates a new scrolling list.
 List(int row)
   Creates a new scrolling list initialized with the
    specified number of visible lines.
 List(int rows, boolean multipleMode)
   Creates a new scrolling list initialized to display
    the specified number of rows.
List
 void add(String item)
    Adds the specified item to the end of scrolling
     list.
 void add(String item, int index)
    Adds the specified item to the the scrolling list
     at the position indicated by the index.
 void addActionListener(ActionListener l)
    Adds the specified action listener to receive
     action events from this list.
List
 void remove( int position)
   Removes the item at the specified position
    from this scrolling list.
 void remove( String item)
   Removes the first occurrence of an item from
    the list.
 void removeAll()
   Removes all items from this list.
List
 void replaceItem(String value, int
  index)
   Replaces the item at the specified index in
    the scrolling list with the new string.
 void select(int index)
   Selects the item at the specified index in the
    scrolling list.
TextArea
 A multi-line region that displays text.
 It can be set to allow editing or to be read-only.
 new TextArea("Hello", 5, 40);
TextArea
 TextArea(int rows, int columns)
   Constructs a new text area with the specified
    number of rows and columns and the empty
    string as text.
 TextArea(String text)
   Constructs a new text area with the specified
    text.
 TextArea(String text, int rows, int
  columns)
   Constructs a new text area with the specified
    text, and with the specified number of rows and
    columns.
TextArea
 TextArea(String text, int rows, int
  columns, int scrollbars)
   Constructs a new text area with the specified
    text, and with the rows, columns, and scroll bar
    visibility as specified.
 void append(String str)
   Appends the given text to the text area's
    current text.
 void insert(String str, int position)
   Inserts the specified text at the specified
    position in this text area.
Types of containers
 Window
   A top-level display surface (a window)
   An instance of the Window class has no border
    and no title
 Frame
   A top-level display surface (a window) with a
    border and title
   An instance of the Frame class may have a
    menu bar
Types of containers
 Dialog
    A top-level display surface (a window) with a
     border and title
    An instance of the Dialog class cannot exist
     without an associated instance of the Frame
     class.
 Panel
    A generic container for holding
     components.
    An instance of the Panel class provides a
     container to which to add components.
FRAMES
 A top-level window with a title and a border.
 It has minimize, maximize, and close buttons in its
  top right corner and can be moved and resized
  (by default)
 Frames are created using the Frame class
FRAMES
 Frame()
     Creates a new instance of Frame that is
      initially invisible
 Frame(String title)
     Creates a new instance of Frame that is
      initially invisible with the specified title
 NOTE: Initially, a frame will not be visible. You
  have to set it to be visible using the
  setVisible() method
FRAMES
 boolean isResizable()
   Returns a boolean value indicating whether a
    frame is resizable or not
 void setResizable(boolean resizable)
   Sets whether or not a frame is resizable
 void isVisible(boolean isVisible)
   Sets whether or not a frame is visible
FRAMES
 String getTitle()
   Returns the title of a frame
 void setTitle(String title)
   Sets the title of a frame
 void setSize(int width, int height)
   Sets the size of a frame
 void setLocation(int xCoord, int
  yCoord)
   Sets the location of the window
Frames
 Frames are capable of generating the following
  types of WindowEvents:
   WINDOW_OPENED
   WINDOW_CLOSING
   WINDOW_CLOSED
   WINDOW_ICONIFIED
   WINDOW_DEICONIFIED
   WINDOW_ACTIVATED
   WINDOW_DEACTIVATED
   WINDOW_GAINED_FOCUS
   WINDOW_LOST_FOCUS
   WINDOW_STATE_CHANGED
Frames — Example
 You can create a frame creating an instance of
  class Frame:
import java.awt.*;
class MyFrame {
    public static void main(){
        Frame frame = new Frame("My
  title");
         frame.setSize(200, 200);
         frame.setVisible(true);
    }}
Dialog
 A top-level window with a title and a border that
  is typically used to take some form of input from
  the user.
 The size of the dialog includes any area
  designated for the border.
 A dialog must have either a frame or another
  dialog defined as its owner when it's constructed.
Dialog
 Dialog(Dialog owner)
   Constructs an initially invisible, non-modal
    Dialog with an empty title and the specified
    owner dialog.
 Dialog(Dialog owner, String title)
   Constructs an initially invisible, non-modal
    Dialog with the specified owner dialog and
    title.
 Dialog(Frame owner)
   Constructs an initially invisible, non-modal
    Dialog with an empty title and the specified
    owner frame.
Dialog
 Dialog(Frame owner, String title)
   Constructs an initially invisible, non-modal
    Dialog with the specified owner frame and
    title.
 String getTitle()
   Gets the title of the dialog.
 void hide()
   Hides the Dialog and then causes show() to
    return if it is currently blocked.
Dialog
 void show()
   Makes the Dialog visible.
 void setResizable(boolean resizable)
   Sets whether this dialog is resizable by the
    user.
 void setTitle(String title)
   Sets the title of the Dialog.
Panel
 The simplest container class
 Provides space in which an application can
  attach any other component, including other
  panels.
 The default layout manager for a panel is the
  FlowLayout layout manager.
Panel
 Panel()
   Creates a new panel using the default layout
    manager.
 Panel(LayoutManager layout)
   Creates a new panel with the specified
    layout manager.
 void add(…)
   Add a component to the panel
 void remove(…)
   Remove a component from the panel
Java event handling
 Event handling in Java refers to executing some
  code when specific actions occur such as a
  window being minimized or a button being
  clicked
 There are special interfaces for this purpose and
  they are located in the java.awt.event package
Handling window events
 To handle window events, the WindowListener
  interface is used
 The class that handle window events must
  implement this interface
 The WindowListener interface has various
  methods to handle window events
 These methods are presented on the following
  slides
Methods of the
WindowListener interface
windowOpened(WindowEvent e)
    Called when a window first becomes visible
windowActivated(WindowEvent e)
    Called when a window has become active
     (meaning it is able to accept input events)
windowDeactivated(WindowEvent e)
    Called when a window is deactivated
     (meaning it has lost input focus)
Methods of the
WindowListener interface
windowIconified(WindowEvent e)
    Called when a window is iconified (minimized)
windowDeiconified(WindowEvent e)
    Called when a window has been restored from a
     minimized state
windowClosing(WindowEvent e)
    Called when a user attempts to close a frame
windowClosed(WindowEvent e)
    Called when a window is closed
Handling action events
 To handle action events (such as the clicking of
  a button), the ActionListener interface is used
 Method of the ActionListener interface:
actionPerformed(ActionEvent e)
    Called when an action has occurred
Handling focus events
 To handle focus events (such as when an object
  such as a textbox is awaiting user input), the
  FocusListener interface is used
 Methods of the FocusListener interface:
focusGained(FocusEvent e)
    Called when an object gains focus
focusLost(FocusEvent e)
    Called when an object loses focus
Handling item events
 Item events are triggered by components that
  allow for a selection of items such as
  Checkboxes
 To handle item events, the ItemListener
  interface is used
 Method of the ItemListener interface:
itemStateChanged(ItemEvent e)
    Called when the state of an item has
     changed
Handling text events
 Text events are triggered by components whose
  fields are editable such as textboxes
 To handle text events, the TextListener
  interface is used
 Method of the TextListener interface:
textValueChanged(TextEvent e)
    Called when the data in a field of a
     component has changed
Handling mouse events
 Mouse events are triggered by the computers
  mouse
 Mouse events are actually handled by two
  interfaces:
    MouseListener: used to detect the
     clicking of mouse buttons or the moving of a
     mouse into or out of a listener's area
    MouseMotionListener: used to detect the
     movement of the mouse
Methods of the
MouseListener interface
mouseClicked(MouseEvent e)
 Called when a mouse button is clicked
mouseEntered(MouseEvent e)
 Called when the mouse enters a source
  components area
Methods of the
MouseMotionListener interface
mouseMoved(MouseEvent e)
 Called when the mouse is moved while in a
  components area
mouseDragged(MouseEvent e)
 Called when the mouse moves while a mouse
  button is down while within a components area
Handling key events
 Key events are triggered by keyboard actions
 Key events are handled by the KeyListener
  interface
 Methods of the KeyListener interface:
keyPressed(KeyEvent e)
    Called when a key is pressed down
keyReleased(KeyEvent e)
    Called when a key is released
keyTyped(KeyEvent e)
    Called when a key is typed
Making objects listen for
events
 Once you implement the necessary interfaces,
  and define the implementation of their methods,
  you need to make objects listen for events
 Example: if you implement the ActionListener
  interface, and you define what its
  actionPerformed() method does, and you
  want the method to be called every time a
  certain button is clicked, you need to make that
  button listen for the event
Listen for action events
 For action events use the addActionListener()
  method
 Example:
//create a button
Button aButton = new Button("This is a
  button");
//specify that this button listens for
  action events
aButton.addActionListener(this);
Listen for action events
 The class that contains the previous button must
  implement the interface ActionListener, so it
  will have a function
  actionPerformed(ActionEvent e)
 You can find the source of this event calling the
  function e.getSource()
 This function will return an element of type
  Object
Listen for focus events
 For focus events use the addFocusListener()
  method
 Example:
//create a textbox
TextField aTextField = new TextField("This
  is a textbox");
/*specify that this textbox listens for
  focus events*/
 aTextField.addFocusListener(this);
Listen for item events
 For item events use the addItemListener()
  method
 Example:
//create a checkbox
CheckBox chkbox1 = new CheckBox("This is a
  checkbox", false);
/*specify that this checkbox listens for
  item events*/
 chkbox1.addItemListener(this);
Listen for text events
 For text events use the addTextListener()
  method
 Example:
//create a textbox
TextField aTextField = new TextField("This
  is a textbox");
/*specify that this textbox listens for
  text events*/
aTextField.addTextListener(this);
Listen for mouse events
 For mouse events use the addMouseListener()
  method
 Example:
//create a frame
Frame aFrame = new Frame();
/*specify that this frame listens for
  mouse events*/
aFrame.addMouseListener(this);
Listen for mouse motion
events
 For mouse motion events use the
  addMouseMotionListener() method
 Example:
//create a frame
Frame aFrame = new Frame();
/*specify that this frame listens for
  mouse motion events*/
aFrame.addMouseMotionListener(this);
Listen for key events
 For key events use the addKeyListener()
  method
 Example:
//create a textbox
TextField aTextField = new TextField("This
  is a textbox");
/*specify that this textbox listens for
  key events*/
aTextField.addKeyListener(this);
References
 Todd Sundsted, Introduction to the AWT. A
  description of Java’s user interface toolkit,
  http://www.javaworld.com/javaworld/jw-07-
  1996/jw-07-awt.html