Docstoc

Java Swing Intro to GUI programming

Document Sample
Java Swing Intro to GUI programming Powered By Docstoc
					Intro to GUI programming with
             Java
                          Model-View-Controller
                       architectural design pattern
Good designs separate data (the „model‟) from its
  presentation (the „view‟)
MVC pattern
   – Provides for a good way to partition work and create a modular
     design
   – Provide multiple ways to look at the same information
MVC componets
   – Model
      • Data storage, no presentation elements
   – View
      • No data storage, presentation elements
   – Controller
      • Glue to tie the model and the view together
Source: sun.com
                                                    Model
• aka Data Model
  – Application state (e.g., storage), not presentation
     • Knows data, not pixels
  – Support data model operations
     • E.g., file saving, history, password, networked data
        – All operations on the model
        – Work out logic for manipulating chat data (e.g., storage of chat
          history) without worrying about pixels
View / Controller
View
  – Presentation layer
       • Gets relevant data from the model
         and renders it for the user
Controller
  – The logic that glues things together
  – Manage the relationship between the model and the
    view
       • Most data changes are initiated by user events. Translated
         into messages to the model
       • The view needs to hear about changes. This is done in Java
         using Listeners
                                             Model Role
• Respond to getter methods to provide data
• Respond to setters to change data
• Manage a list of listeners
  – When data changes notify call listeners to notify the
    change
     • Iterate through the listeners and notify each about the
       change
     • fireXXXChanged()
           A possible source of confusion
• Model-View-Controller design is applied at two
  levels
  – Your own code should use this design
  – Java GUIs (Swing) components use the design
    themselves
Java … and practical issues
                               Coding „by hand‟ vs.
                                  GUI editors
You still need to understand the basics
  --> Build at least one GUI by hand


GUI editor pros
  – Programming productivity
GUI editor cons
  – Learning curve
  – Possible vendor lock-in
  – Complex layouts still require good understanding of
    swing concepts.
                                                     AWT vs.
• AWT: Abstract Windowing Toolkit                     Swing
     • import java.awt.*
     • AWT drawing uses "native peers" -- creating an AWT button
       creates a native peer (Unix, Mac, Win32) button to put on
       screen, and then tries to keep the AWT button and the peer in
       sync.
     • Advantage: an AWT app has the "native" appearance for
       buttons etc. since there are in fact native buttons on screen.
     • Disadvantage: very hard to implement in a reliable way --
       keeping peers consistent on all platforms.
• Swing: new with Java2
     •   import javax.swing.*
     •   Extends AWT
     •   Standard dialog boxes, tooltips, …
     •   Look-and-feel, skins
     •   Event listeners
• API: http://java.sun.com/j2se/1.5.0/docs/api/
           GUI Component API

• Java: GUI component = class

• Properties
     •
                                JButton
• Methods
     •
• Events
     •
           Using a GUI Component
1.   Create it
      •   Instantiate object: b = new JButton(“press me”);
2. Configure it
      •   Properties: b.text = “press me”;
      •   Methods:    b.setText(“press me”);
3. Add it
      •   panel.add(b);
4. Listen to it
      •   Events: Listeners
                                                   JButton
      Anatomy of an Application GUI
            GUI                  Internal structure


JFrame                                JFrame
 JPanel             containers

                                      JPanel
          JButton


                             JButton           JLabel
           JLabel
       Using a GUI Component (II)
1.   Create it
2.   Configure it
3.   Add children (if container)     the order IS
4.   Add to parent (if not JFrame)   important
5.   Listen to it
             Build from bottom up
• Create (order indifferent):
     •   Frame                              Listener
     •   Panel
     •   Components
     •   Listeners                 JLabel   JButton
• Build: (aggregate bottom up)
     • listeners into components
     • components into panel           JPanel
     • panel into frame




                                       JFrame
                       Code
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);

p.add(b);                  // add button to panel
f.setContentPane(p);   // add panel to frame

f.setVisible (true);




                                       press me
          (trivial) Application Code
import javax.swing.*;

class hello {
  public static void main(String[] args){
     JFrame f = new JFrame(“title”);
     JPanel p = new JPanel();
     JButton b = new JButton(“press me”);

        p.add(b);      // add button to panel
        f.setContentPane(p);// add panel to frame

        f.setVisible (true);         press me
    }
}
            Layout Managers
• Automatically control placement of components
  in a panel
• Why?
     •
              Layout Manager Heuristics
        null             FlowLayout        GridLayout


        none,
                         Left to right,
    programmer
                        Top to bottom
     sets x,y,w,h


BorderLayout             CardLayout       GridBagLayout
     n

w         c         e   One at a time          JButton

          s
  Combinations


JButton JButton




       JTextArea
                   Combinations

                             JButton    JButton
JFrame
              n             JPanel: FlowLayout
     JPanel: BorderLayout


              c
                                JTextArea
      Our code so far: null layout
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);

b.setBounds(new Rectangle(10,10, 100,50));
p.setLayout(null);            // x,y layout
p.add(b);
f.setContentPane(p);




                                       press me
           Code: FlowLayout
JFrame f =   new JFrame(“title”);
JPanel p =   new JPanel( );
FlowLayout   L = new FlowLayout( );
JButton b1   = new JButton(“press me”);
JButton b2   = new JButton(“then me”);

p.setLayout(L);
                                press me then me
p.add(b1);
p.add(b2);
f.setContentPane(p);

Set layout mgr before adding components
     (Recap) Using a GUI Component
1.   Create it
2.   Configure it
3.   Add children (if container)     the order IS
4.   Add to parent (if not JFrame)   important
5.   Listen to it
                                                         Callbacks
JButton b = new JButton(…)                                (again)
b.addActionListener(new MyButtonListener());

A listener implements ActionListener interface
        – sole method: void actionPerformed (ActionEvent e)

class MyButtonListener implements ActionListener {
   void actionPerformed(ActionEvent e) {
           CALLBACK: your code to
           -- obtain the details of the event, and
           -- react appropriately
    }
}


Often implemented an inner class if you need access to
  otherwise private fields in the GUI
Example
                         Summary
Model-View-Controller design
Building GUIs form individual components
     1.   Create component
     2.   Configure it
     3.   Add children (if container)
     4.   Add to parent (if not JFrame)
     5.   Listen to it
              -- Another use of callbacks again
                                            Discussion
• Build GUI in main() vs. JFrame or JPannel
  subclass
• Threading: at least three threads that are
  typically used in a GUI application.
  – Initial thread - This is the thread that start main.
    Stops when main returns.
  – Event Dispatch Thread (EDT) - Initializes and runs
    the GUI, and calls listeners.
  – Worker threads - These should be started for any
    slow listener.
Backup slides
                      Clean initialization
•   import javax.swing.*;

•   ////////////////////////////////////////////////////// class TinyWindow2
•   class TinyWindow2T extends JFrame {

•       //====================================================== method main
•       public static void main(String[] args) {
•         SwingUtilities.invokeLater(new Runnable() { //Note 1
•             public void run() {
•               TinyWindow2T window = new TinyWindow2T();
•               window.setVisible(true);
•             }
•         });
•       }
•
•       //====================================================== constructor
•       public TinyWindow2T() {
•         //... Set window characteristics
•         setTitle("Tiny Window using JFrame Subclass");
•         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
•       }
•   }

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:441
posted:4/9/2010
language:English
pages:30