Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI.

Slides:



Advertisements
Similar presentations
Introduction to Swing Components Chapter 14. Part of the Java Foundation Classes (JFC) Provides a rich set of GUI components Used to create a Java program.
Advertisements

Graphical User Interfaces
Graphical User Interfaces Java’s AWT and Swing APIs.
Graphical User Interfaces (Part IV)
Java Software Development Paradigm Lecture # 12. Basics of GUI.
CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Graphical User Interface (GUI) Programming III. Lecture Objectives Exploring more GUI programming elements in Java Using labels in GUIs Using colors to.
GUI and Event-Driven Programming Recitation – 3/6/2009 CS 180 Department of Computer Science, Purdue University.
Chapter 121 Window Interfaces Using Swing Chapter 12.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
CS102--Object Oriented Programming Lecture 18: – The Swing Package Copyright © 2008 Xiaoyan Li.
Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
Java Swing. Introduction to Swing A GUI (graphical user interface) is a windowing system that interacts with the user The Java AWT (Abstract Window Toolkit)
Java Programming Chapter 10 Graphical User Interfaces.
Programming With Java ICS201 University Of Ha’il1 Chapter 17 Graphical User Interfaces Swing I.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Chapter 12- GUI’s, Java, and Swing.. Overview n What are GUI’s n How Java does GUI’s- Swing n Buttons n Containers n Text I/O and Swing n Review.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 13 : Swing I King Fahd University of Petroleum & Minerals College of Computer Science.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
University of Limerick1 Software Architecture Java Layout Managers.
CS1054: Lecture 21 - Graphical User Interface. Graphical User Interfaces vs. Text User Interface.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
Chapter 17 Swing I Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Christopher Budo, Davis Nygren, spencer franks, Luke miller
A First Look at GUI Applications
Graphical User Interface Programming
Graphical User Interface (pronounced "gooey")
Graphical User Interface (GUI) Programming III
Chapter 17 Swing I Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc. All.
Chap 7. Building Java Graphical User Interfaces
MSIS670: Object-Oriented Software Engineering
Graphical User Interface
Presentation transcript:

Graphical User Interface Programming

GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI programming Java GUI programming AWT (Abstract Window Toolkit) AWT (Abstract Window Toolkit) Swing Swing

Event driven programming Uses a signal-and-response approach Uses a signal-and-response approach Events and event handlers Events and event handlers Asynchronous Asynchronous Event = object that act as a signal to another object Event = object that act as a signal to another object Listener = event receiver Listener = event receiver One event might have zero or more listeners. One event might have zero or more listeners. Listeners can receive events from different objects. Listeners can receive events from different objects.

Event driven programming One event might have zero or more listeners. One event might have zero or more listeners. Button X Listerner A Listerner B Listerner C

Event driven programming Listeners can receive events from different objects. Listeners can receive events from different objects. Button Y Button Z Button X Listerner A Listerner B

Typical events User moves the mouse. User moves the mouse. User clicks the mouse button. User clicks the mouse button. User clicks the mouse button in a button in a window. User clicks the mouse button in a button in a window. User presses a key on the keyboard. User presses a key on the keyboard. Timer event occurs. Timer event occurs.

Typical programming and event driven programming Up to now your programs consisted of lists of statements executed in order. 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. 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. You don’t know the order ahead of time. Typically, your code never directly calls the listener methods. 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. Smallest unit of space on which your screen can write. Contraction for … what? Contraction for … what?

Useful JFrame methods public JFrame ( ) public JFrame ( ) public JFrame ( String title ) public JFrame ( String title ) public void setDefaultCloseOperation ( int operation ) public void setDefaultCloseOperation ( int operation ) JFrame.DO_NOTHING_ON_CLOSE JFrame.DO_NOTHING_ON_CLOSE JFrame.HIDE_ON_CLOSE JFrame.HIDE_ON_CLOSE JFrame.DISPOSE_ON_CLOSE JFrame.DISPOSE_ON_CLOSE JFrame.EXIT_ON_CLOSE JFrame.EXIT_ON_CLOSE Note: The close-window-button is part of the JFrame (not a JButton) Note: The close-window-button is part of the JFrame (not a JButton) public void setSize ( int width, int height ) public void setSize ( int width, int height )

More useful JFrame methods public void setTitle ( String title ) public void setTitle ( String title ) public void add ( Component componentAdded ) public void add ( Component componentAdded ) public void setLayout ( LayoutManager manager ) public void setLayout ( LayoutManager manager ) public void setJMenuBar ( JMenuBar menubar ) public void setJMenuBar ( JMenuBar menubar ) public void dispose ( ) public void dispose ( ) public void setVisible ( boolean makeVisible ) 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. 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. 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 f.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); … f.setVisible( true ); This is not a very OO approach!

A more OO approach to creating a window in Swing import javax.swing.JFrame; public MyFrame extends JFrame { public static final intsWidth = 300; public static final intsHeight = 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. 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 Also Color.BLUE, Color.CYAN, Color.DARK_GRAY, … 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. 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. Use getContentPane().setBackground( Color.BLUE ); to change the background color of your JFrame.

Programming in color Colors are represented by their RGB value. Colors are represented by their RGB value. R=red R=red G=green G=green B=blue B=blue When R is the largest value, the color has more red than the other components. What happens when r=g=b? 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) 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. So far, we simply add components to a container and accept whatever default layout is presented. Layout manager – describes how the components are arranged. Layout manager – describes how the components are arranged. Java provides many layout managers. Java provides many layout managers. Border (in book) Border (in book) Box (not in book) Box (not in book) Card (not in book) Card (not in book) Flow (in book) Flow (in book) Grid (in book) Grid (in book) Grid bag (not in book) Grid bag (not in book) Group (not in book) Group (not in book) Spring (not in book) Spring (not in book)

BorderLayout Places the components in five areas: Places the components in five areas: 1. North 2. South 3. East 4. West 5. Center You specify the area in the add method. You specify the area in the add method. add( new JLabel(“me”), BorderLayout.NORTH ); 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. Simplest. Arranges components one after another from left to right and top to bottom in the order in which one adds them. 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). 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. Each entry in the grid will be stretched to the same size.

Placement rules are more complicated. Placement rules are more complicated. Say we have a 2 x 3 (2 rows x 3 cols): Say we have a 2 x 3 (2 rows x 3 cols): new GridLayout( 2, 3 ) new GridLayout( 2, 3 ) If we subsequently add six things, they will appear in a 2x3 grid of equally sized elements. 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? What happens if we add more or less? GridLayout

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

GridLayout Placement rules are more complicated. Placement rules are more complicated. Say we have a 2 x 3 (2 rows x 3 cols). 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 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. 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 FlowLayout Displays components from left to right in the order in which they are added to the container. Displays components from left to right in the order in which they are added to the container. BorderLayout BorderLayout Displays the components in five areas: N, S, E, W, and Center. You specify the area in the add method. Displays the components in five areas: N, S, E, W, and Center. You specify the area in the add method. GridLayout GridLayout Lays out components in a grid with each component stretched to fill its box in the grid. Lays out components in a grid with each component stretched to fill its box in the grid.

Additional Layout Managers Box (not in book) Box (not in book) Card (not in book) Card (not in book) Tabbed pane (not in book; not strictly a layout manager) Tabbed pane (not in book; not strictly a layout manager) Grid bag (not in book) Grid bag (not in book) Group (not in book) Group (not in book) Spring (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 t/box.html

CardLayout Typically used to switch between different panels. Typically used to switch between different panels. Poor man’s version of tabbed pane. Poor man’s version of tabbed pane. choice here causes change here

JTabbedPane Not strictly a layout manager. Not strictly a layout manager. Typically preferred over CardLayout. 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

GroupLayout Intended to be used by GUI builder.

SpringLayout Intended to be used by GUI builder. Intended to be used by GUI builder.

JPanel a general purpose window-like container

Panels (JPanel) General purpose, window-like container General purpose, window-like container Groups objects Groups objects Components may be added to them (including other panels) Components may be added to them (including other panels) hierarchical hierarchical Layout manager can be associated w/ a panel Layout manager can be associated w/ a panel Can be added to a JFrame 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; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.FlowLayout; import java.awt.Color; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class PanelDemo extends JFrame implements ActionListener { public static final int WIDTH = 300; public static final int WIDTH = 300; public static final int HEIGHT = 200; public static final int HEIGHT = 200; private JPanel redPanel = new JPanel(); private JPanel redPanel = new JPanel(); private JPanel whitePanel = new JPanel(); private JPanel whitePanel = new JPanel(); private JPanel bluePanel = new JPanel(); private JPanel bluePanel = new JPanel(); public static void main ( String[] args ) { public static void main ( String[] args ) { PanelDemo gui = new PanelDemo( ); PanelDemo gui = new PanelDemo( ); gui.setVisible( true ); gui.setVisible( true ); } public void actionPerformed ( ActionEvent e ) { public void actionPerformed ( ActionEvent e ) { String buttonString = e.getActionCommand(); String buttonString = e.getActionCommand(); if (buttonString.equals("Red")) if (buttonString.equals("Red")) redPanel.setBackground( Color.RED ); redPanel.setBackground( Color.RED ); else if (buttonString.equals("White")) else if (buttonString.equals("White")) whitePanel.setBackground(Color.WHITE); whitePanel.setBackground(Color.WHITE); else if (buttonString.equals("Blue")) else if (buttonString.equals("Blue")) bluePanel.setBackground( Color.BLUE ); bluePanel.setBackground( Color.BLUE ); else else System.out.println( "Unexpected error.“ ); System.out.println( "Unexpected error.“ ); }

JPanel Example public PanelDemo ( ) { public PanelDemo ( ) { super( "Panel Demonstration“ ); super( "Panel Demonstration“ ); setSize( WIDTH, HEIGHT ); setSize( WIDTH, HEIGHT ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout( ) ); setLayout( new BorderLayout( ) ); JPanel biggerPanel = new JPanel( ); JPanel biggerPanel = new JPanel( ); biggerPanel.setLayout( new GridLayout(1, 3) ); biggerPanel.setLayout( new GridLayout(1, 3) ); redPanel.setBackground( Color.LIGHT_GRAY ); redPanel.setBackground( Color.LIGHT_GRAY ); biggerPanel.add( redPanel ); biggerPanel.add( redPanel ); whitePanel.setBackground( Color.LIGHT_GRAY ); whitePanel.setBackground( Color.LIGHT_GRAY ); biggerPanel.add( whitePanel ); biggerPanel.add( whitePanel ); bluePanel.setBackground( Color.LIGHT_GRAY ); bluePanel.setBackground( Color.LIGHT_GRAY ); biggerPanel.add( bluePanel ); biggerPanel.add( bluePanel ); add( biggerPanel, BorderLayout.CENTER ); add( biggerPanel, BorderLayout.CENTER ); JPanel buttonPanel = new JPanel( ); JPanel buttonPanel = new JPanel( ); buttonPanel.setBackground( Color.LIGHT_GRAY ); buttonPanel.setBackground( Color.LIGHT_GRAY ); buttonPanel.setLayout( new FlowLayout( ) ); buttonPanel.setLayout( new FlowLayout( ) ); JButton redButton = new JButton( "Red“ ); JButton redButton = new JButton( "Red“ ); redButton.setBackground( Color.RED ); redButton.setBackground( Color.RED ); redButton.addActionListener( this ); redButton.addActionListener( this ); buttonPanel.add( redButton ); buttonPanel.add( redButton ); JButton whiteButton = new JButton( "White“ ); JButton whiteButton = new JButton( "White“ ); whiteButton.setBackground( Color.WHITE ); whiteButton.setBackground( Color.WHITE ); whiteButton.addActionListener( this ); whiteButton.addActionListener( this ); buttonPanel.add( whiteButton ); buttonPanel.add( whiteButton ); JButton blueButton = new JButton( "Blue“ ); JButton blueButton = new JButton( "Blue“ ); blueButton.setBackground( Color.BLUE ); blueButton.setBackground( Color.BLUE ); blueButton.addActionListener( this ); blueButton.addActionListener( this ); buttonPanel.add( blueButton ); buttonPanel.add( blueButton ); add( buttonPanel, BorderLayout.SOUTH ); add( buttonPanel, BorderLayout.SOUTH ); }}

JPanel Example PanelDemo (JFrame w/ BorderLayout) PanelDemo (JFrame w/ BorderLayout) biggerPanel (w/ GridLayout of 1 row & 3 cols) biggerPanel (w/ GridLayout of 1 row & 3 cols) added at center added at center redPanel redPanel whitePanel whitePanel bluePanel bluePanel buttonPanel (w/ FlowLayout) buttonPanel (w/ FlowLayout) added at south added at south redButton redButton whiteButton whiteButton blueButton blueButton

The Container class Can have components added to it Can have components added to it JFrame & JPanel are descendents of Container JFrame & JPanel are descendents of Container Container class = any descendent of Container Container class = any descendent of Container Component = any descendent of JComponent Component = any descendent of JComponent You may add any component to any container You may add any component to any container JComponent is derived from Container so you may add a JComponent to a JComponent 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 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). 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. 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 View Renders the model into a form suitable for interaction, typically a user interface element. 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. Multiple views can exist for a single model for different purposes.

Model-View-Controller (from wikipedia.org) Controller Controller Processes and responds to events, typically user actions, and may invoke changes on the model. Processes and responds to events, typically user actions, and may invoke changes on the model.

Basic MVC Model data1 data2. View … update() … Controller … manipulate notify

Model-View-Controller (from wikipedia.org) Though MVC comes in different flavors, control flow generally works as follows: 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. 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

Model (data) ConnectFour | V MyConnectFour View (output) MyView Main Controller (input events) 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… Some designers combine/simply the M-V-C to D-V where… D is the document, data, or model, D is the document, data, or model, V is the View, and V is the View, and the controller is typically part of the view. the controller is typically part of the view.

Menus and buttons

Menu bars, menus, and menu items JMenuBar, JMenu, and JMenuItem JMenuBar, JMenu, and JMenuItem import: import: javax.swing.JMenuBar javax.swing.JMenuBar ex. the menu bar in an app ex. the menu bar in an app javax.swing.JMenu javax.swing.JMenu ex. File ex. File ex. Edit ex. Edit ex. Help ex. Help javax.swing.JMenuItem javax.swing.JMenuItem ex. Open in the File menu ex. Open in the File menu ex. Cut in the Edit menu ex. Cut in the Edit menu implement ActionListener for events 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. When we create a button or menu item, we specify a string. By default, that string becomes the action command for that button. By default, that string becomes the action command for that button. The action command is provided to the actionPerformed method. 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). 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.) 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. A field that allows the user to enter a single line of text. Ex. 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) 30 is the minimum number of visible characters (more may be entered)

Text area (JTextArea) Same as text field except it allows multiple lines. Same as text field except it allows multiple lines. Ex. 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 String getText() public boolean isEditable() public boolean isEditable() public void setBackground ( Color theColor ) public void setBackground ( Color theColor ) public void setEditable ( boolean argument ) public void setEditable ( boolean argument ) public void setText ( String text ) public void setText ( String text )