Docstoc

java_gui

Document Sample
java_gui Powered By Docstoc
					Java: AWT/Swing

  Kannan Balasubramanian
     Sun Microsystems
AWT
Objectives
 Abstract Window Toolkit (AWT)
 Containers, Components and Layout
 Managers
 Events and Event Handling
Building Java GUI
Abstract Window Toolkit
 Provides graphical user interface
 (GUI) components.
 Contains classes that can be
 extended and inherited.
 Every GUI component displayed
 on screen is subclass of
 Component or MenuComponent.
 Has Container class which is
 subclass of Component and
 includes two subclasses.
  Panel
  Window
java.awt Package                                       PopupMenu


                          MenuBar        Menu
         MenuComponent
                          MenuItem       CheckboxMenuItem

Object                                                 Applet
                         Button
                         Canvas
                         Checkbox
         Component       Choice
                         Container        Panel          Frame
                         Label            Window         Dialog
                         ScrollBar        ScrollPane
                         TextComponent
                                                       FileDialog

                                          TextArea
                                          TextField
Containers
Add components with the add() method.
Two main types of containers are Window and
Panel.
A Window is a free floating window on the
display. Two important types of Window:
 Frame
 Dialog
A Panel is a container of GUI components that
must exist in the context of some other container
such as Window or Applet.
Building Graphical User Interfaces
 The position and size of a component in a
 container is determined by a layout manager.
 Size or position of a component can be
 controlled by disabling the layout manager.
 Use setLocation, setSize() or setBounds() on
 components to locate components in the
 container.
Frame

Subclass of Window.
Have Title and resizing corners.
Are initially invisible, use setVisible(true) to show
them.
Have BorderLayout as the default layout maneger.
Use setLayout() method to change the default
layout manager.
Frame Example
Import java.awt.*;
public class FrameExample {
   private Frame f;
   public FrameExample() {
     f = new Frame(“Hello Out There!”);
   }
   public void launchFrame() {
     f.setSize(170, 170);
     f.setBackground(Color.blue);
     f.setVisible(true);
   }
   public static void main(String args[]) {
     FrameExample guiWindow = new FrameExample();
     guiWindow.launchFrame();
  }
}
Panel
 Panel is contained within another Container.
 Provide space for Components.
 FlowLayout is the default layout manager.
 Allow subpanels to have their own layout
 manager.
Dialog
 It is a free standing window without the resizing
 corners.
 Two types of Dialog:
   Modeless: Allows the user to interact with other
   windows also.
   Model: Doesn't allow to interact with other windows
   until it is closed
 Dialog d = new Dialog(f, “Dialog”, true);
 Button bt = new Button(“OK”);
 d.add(bt);
 d.pack();
 d.setVisible(true);
AWT Components
Button
  frame = new Frame("Button Sample");
  button = new Button("Button");

  button.addActionListener(this);
  frame.add(button);

  frame.setSize(200, 200);
  frame.setVisible(true);
Checkbox
Frame = new Frame("Checkbox Sample");
checkbox1 = new Checkbox("One", true);
checkbox2 = new Checkbox("Two", false);
checkbox3 = new Checkbox("Three", false);
checkbox1.addItemListener(this);
checkbox2.addItemListener(this);
checkbox3.addItemListener(this);
frame.setLayout(new FlowLayout());
frame.add(checkbox1);
frame.add(checkbox2);
frame.add(checkbox3);
CheckboxGroup
frame = new Frame("CheckBoxGroup Sample");
group = new CheckboxGroup ();
checkbox1 = new Checkbox("One", group, true);
checkbox2 = new Checkbox("Two", group, false);
checkbox3 = new Checkbox("Three", group, false);

checkbox1.addItemListener(this);
checkbox2.addItemListener(this);
checkbox3.addItemListener(this);

frame.setLayout(new FlowLayout());
frame.add(checkbox1);
frame.add(checkbox2);
frame.add(checkbox3);
Choice
frame = new Frame("Choice Sample");
choice = new Choice();

choice.addItemListener(this);

choice.add("First");
choice.add("Second");
choice.add("Third");

frame.add(choice);
TextField
Frame = new Frame("TextField Sample");
tf = new TextField ("Enter Text", 30);

tf.addActionListener(this);
frame.add(tf);

frame.setSize(200, 70);
frame.setVisible(true);
List
frame = new Frame("List Sample");
list = new List(4, true);

list.addItemListener(this);

list.add("First");
list.add("Second");
list.add("Third");

frame.add(list);
How to create a Menu
 Create a MenuBar Object and set it into
 menu container such as a Frame
 Create one or more Menu objects and add
 them to menu bar object
 Create one or more MenuItem objects and
 add them to menu object

 Frame f = new Frame(“MenuBar”);
 MenuBar mb = new MenuBar();
 Menu m1= new Menu(“File”);
 mb.add(m1);
 f.setMenuBar(mb);
Controlling Visual Aspects

  Colors:
  setForeground();
  setBackground();
  Fonts:
  setFont();

 Font ft = new Font(“TimesRoman”, Font.PLAIN, 14);
 comp.setFont(ft);
Toolkit class
Toolkit class is an abstract superclass of all
platform- specific implementations of the
Abstract Window Toolkit
    getDefaultToolkit - Returns current toolkit
    object
    getImage(String fileName) – Loads an image
    from file
    getScreenResolution – Returns number of
    “pixels per inch”
    getScreenSize – Returns Dimension object
    having width and height of screen in pixels
    getPrintJob – Returns PrintJob object
Printing
Following code fragment prints a Frame

Frame frame = new Frame(“Print Test”);
Toolkit toolkit = frame.getToolkit();
PrintJob job = toolkit.getPrintJob(frame, “Test Printing”, null);
Graphics g = job.getGraphics();
frame.printComponents(g);
g.dispose();
job.end();
Layouts
 FlowLayout
 BorderLayout
 GridLayout
 CardLayout
 GridBagLayout
Default Layout Managers
                     Component

                     Container


          Window                  Panel

                                   Applet
  Frame             Dialog
                                 FlowLayout

     BorderLayout
FlowLayout Manager
  Positions components on a line by line basis
  Default Layout Manager for Panel Class
  Components added from left to right
  Default alignment is centered
  Uses components preferred sizes

setLayout(new FlowLayout(int align, int hgap, int
 vgap));
BorderLayout Manager
  It has five distinct areas: NORTH, SOUTH,
  EAST, WEST and CENTER
  Default Layout Manager for Frame and Dialog
  Classes
  Components are added to specific regions
  The Resizing behaviour:
    North, South and Center regions adjust
    horizontally.
    East, West and Center regions adjust
    vertically.
SetLayout( new BorderLayout(int hgap, int
 vgap) );
GridLayout Manager
  It divides whole area into cells
  Components are added left to right, top to
  bottom.
  All regions are equal`ly sized.
  The constructor specifies the rows and columns.

SetLayout( new GridLayout(int rows, int cols) );``
CardLayout Manager
  It treats the interface as a series of
  cards
  Only one card can be viewed at any
  time
  add() method is used to add cards to
  CardLayout

SetLayout( new CardLayout() );
Drawing in AWT
 We can draw in any Component
 although AWT provides Canvas class
 for drawing
 paint() method for drawing
 paint method is called everytime the
 component is shown
 Every Component has a Graphics
 object
 Graphics class implements many
 drawing methods
GUI Event Handling
What is an Event?
 Events:
 Objects that describe what happened
 Event sources:
 The generator of an event
 Event Handlers:
 Method that receives an event object and
 processes the user interaction
  Frame
                            User clicks button


          Button
                       ActionEvent

                                                 Event Handler
Delegation Model
 Client objects register with a GUI
 component they want to register
 GUI components only trigger the
 handlers for the type of event that
 has occurred
 Delegation model distributes the work
 among multiple classes
Event Categories
                                            java.awt.event

                                               ActionEvent
                                                                FocusEvent
                        Java.awt.AWTEvent
Java.util.EventObject




                                             AdjustmentEvent     InputEvent      KeyEvent
                                                               ContainerEvent   MouseEvent
                                              ComponentEvent
                                                               WindowEvent
                                                 ItemEvent


                                                 TextEvent
Event Categories
  Category     Interface Name
Action         ActionListener

Item           ItemListener

Mouse          MouseListener

Mouse Motion   MouseMotionListener

Key            KeyListener

Focus          FocusListener

Adjustment     AdjustmentListener

Component      ComponentListener

Window         WindowListener

Container      ContainerListener

Text           TextListener
Multiple Listeners
 Multiple listeners cause unrelated
 parts of a program to react to the
 same event
 The handlers of all registered listeners
 are called when the event occurs
Event Adapters
 The user defined listener classes can
 extend adapter classes and override the
 methods that are needed
 Adapter classes implement each
 interface containing more than one
 method and provide empty
 implementation of methods
Swing
Swing
 Swing is a second generation GUI Toolkit
 It is built on top of AWT and provides
 lightweight version of components
 Provides several more components:
   - JTable
   - JTree
   - JEditorPane
   - JScrollPane
   - JSpinner ...
MVC Architecture
●MVC – Model – View – Controller
   - Model – Data for Application
   - View – Visual representation of data to the user
   - Controller – Takes user input on view. Translates that
changes in model.
Swing Architecture
 - View and Controller are tightly coupled
 - Most user interactions are hand led by AWT

   UIDelegate
   - View and Controller collapsed to form single
entity
   - Delegates some of component's
view/controller responsibilities to LAF (Look and
Feel) specific objects provided by PLAF
architecture.
Swing Classes
● JComponent
   - Base class for all swing components except top level
containers
   - Handles PLAF, Double buffering, Keystrokes, Accessibility
● UIManager


   - Keep track of current LAF
   - Default values – User, LAF, System
   - Set new Look and Feel
● UIDefaults


   - Stores default values like Color, Font, Icons ...
   - The values can be set from UIManager
Swing Classes Ctd.
●
    Component UI
  - Base class of all UI Delegate objects
  - JComponent class invokes methods in this class so as to
delegate operations such as painting, layout calculations etc...

● SwingUtilities
   - A very useful class that provides lots of useful methods
while rendering application, wiring components together or even
implementing infrastructure of an application.
JTree
JColorChooser
Color color =
JColorChooser.showDialog(frame,"
ChooseBackgroundColor",Color.Re
d);
 JSlider
JSlider slider3 = new JSlider();
slider3.setBorder(BorderFactory.cr
eateTitledBorder("JSlider with Tick
Marks & Labels"));
slider3.setMajorTickSpacing(20);
slider3.setMinorTickSpacing(5);
slider3.setPaintTicks(true);
slider3.setPaintLabels(true);
Double Buffering
 - Swing uses double buffering by default
   - This avoids flickering/flashing images.

 - To turn on/off double buffering at application level
    RepaintManager.setDoubleBufferingEnabled(boolean
bFlag)

  - Turn off double buffering before printing a swing
component for better printing quality and performance.
Look And Feel
●    Different Look and Feels supported by swing
    - Java L&F (Cross Platform Look and Feel)
    - Windows L&F
    - Motif L&F
    - GTK L&F
    - Synth L&F

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName(
));

UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
Windows LAF
Motif LAF
Java LAF
Simple Swing Application
private static void createAndShowGUI() {
  Jframe frame = new JFrame("FocusConceptsDemo");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane(new JButton(“Click me”));
  frame.setSize(400, 400);
  frame.setVisible(true);
}
public static void main(String[] args) {
  javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
  });
}
AWT vs Swing
● AWT
    – Platform Dependent Behavior
    – Not customizable
    – Limited Components
    – Missing features like ToolTip, Icons
    – Heavy Weight Component
● Swing


    – Pure Java Design. Platform Independent.
    – Pluggable Look And Feel (PLAF)
    – Customizable Components
    – Provides more features and higher level components (JTable,
JTree...)
    – Light Weight Components
           Thank You!


kannan.balasubramanian@sun.com
Sun Microsystems

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:38
posted:1/21/2011
language:English
pages:54