Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface.

Slides:



Advertisements
Similar presentations
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
GUI and Event-Driven Programming Recitation – 3/6/2009 CS 180 Department of Computer Science, Purdue University.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CPSC150 JavaLynn Lambert CPSC150 Week 12 InheritanceInterfaces.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Java Programming Chapter 10 Graphical User Interfaces.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Intro to Java 2 By Geb Thomas Based on the Java TutorialJava Tutorial.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
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.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
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.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
University of Limerick1 Software Architecture Java Layout Managers.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Computer Science 209 GUIs Model/View/Controller Layouts.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
CSC 205 Programming II Lecture 5 AWT - I.
Object-Orientated Analysis, Design and Programming
Graphical User Interfaces
A First Look at GUI Applications
GUIs Model/View/Controller Layouts
A Quick Java Swing Tutorial
Ellen Walker Hiram College
A Quick Java Swing Tutorial
Graphical User Interface
Presentation transcript:

Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface in Java using Swing; –find out how to use components by browsing the Swing Tutorial and the Java API; –program listeners to respond to user generated events; –use layout managers to arrange components attractively in windows

Introduction Up till now you have written programs that communicate with the end user through a text-based interface –Using System.out for output –Using Keyboard for input. Java provides two sets of facilities for developing GUIs: –The Abstract Window Toolkit (AWT): package java.awt –Swing: package javax.swing

Understanding events Text-based interface Predetermined sequence of events The program pauses execution when it expects input from the user and continues on the same set path after it receives the input Graphical interface No set sequence of events The user can do any number of things at any time (type in a text box, resize the window, press a button) These responses are called events. We say the program is event-driven.

A first Swing application import javax.swing.*; public class FirstGUI { public static void main(String[] args) { JFrame f = new JFrame(); f.setVisible(true); } When you run this program, a tiny window appears: The close button does not work (have to press “Stop” in Ready) Class for drawing a window on the screen Displays the window and enters the event loop.

Shutting down the application properly import javax.swing.*; public class FirstGUI { public static void main(String[] args) { JFrame f = new JFrame( ); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } To give the application a title, give the constructor a string: JFrame f = new JFrame( “My first GUI”); Need to add a single statement to program the close button

Components and containers A component is any GUI element, such as a window, button or label. A container is a type of component that has the purpose of containing other components. Types of containers: –Top-level containers: Every Swing program contains at least one top-level container (e.g. JFrame, JDialog or JApplet ). Top-level containers cannot be added to other containers. –Intermediate containers: used to group components so that they can be handled as a single component (e.g JPanel, JTabbedPane ). –Atomic components (basic controls): cannot contain other components (e.g JButton, JTextField ).

Examples of Atomic Components Often called widgets: Label – used to put a label next to another component Button – used to make the program “do something” Checkbox component – used for yes/no, true/false response from user Choice component – drop-down list TextField – used to type single line of text … etc

Adding a button to the application import javax.swing.*; public class FirstGUI { public static void main(String[] args) { JFrame f = new JFrame( ); JButton button = new JButton("Press me!"); // create a button f.getContentPane().add(button); // add the button to the frame f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack( ); f.setVisible(true); }

Organising the code in a better way As we start adding more components, the main method will become too large and messy. A better way: –Create a class that extends JFrame –Put all components into the class (as data members) –Do the rest in the constructor import javax.swing.*; public class SimpleFrame extends JFrame { private JButton button = new JButton("Press me!"); public SimpleFrame( ) { getContentPane( ).add(button); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

Creating a SimpleFrame object SimpleFrame extends JFrame, therefore s is also a JFrame object (and so we can call the setVisible method). In the SimpleFrame class: –SimpleFrame defines a specialisation of JFrame by adding an additional component. –To call methods of JFrame (such as getContentPane or pack ), we no longer need an object handle, since these methods are now inherited from JFrame ). public class FirstGUI { public static void main(String[] args) { SimpleFrame s = new SimpleFrame( ); s.setVisible(true); }

Adding a label To add a label to our application: –Create a background, which has both components on it –Add this background to our frame In Swing, such a “background” is a component called a panel ( JPanel ). The diagram on the right is called a component hierarchy (shows how the components fit together) SimpleFrame : (contentPane) JLabel (label) JPanel (background) JButton (exit)

Modified code import javax.swing.*; public class SimpleFrame extends JFrame { private JButton button = new JButton("Press me!"); private JLabel label = new JLabel("Go on, press the button"); private JPanel background = new JPanel(); public SimpleFrame() { background.add(button); // add button to background background.add(label); // add label to background getContentPane().add(background); // add background to frame setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } JLabel used for placing plain text on a GUI JPanel is an intermediate container

Getting the button to do something Currently, if the user clicks on our button, nothing happens. We would like to change the program, so that the label changes when the button is clicked: The code that responds to that event of the user clicking the mouse on our button is called the listener for that button. We would therefore like to program the listener of the button to have the code: label.setText(" Ouch... that hurt! ");

import javax.swing.*; import java.awt.event.*; public class SimpleFrame extends JFrame { private JButton button = new JButton("Press me!"); private JLabel label = new JLabel("Go on, press the button"); private JPanel background = new JPanel(); public SimpleFrame() { button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // code to be executed when button is pushed label.setText("Ouch... that hurt! "); } }); background.add(button); background.add(label); getContentPane().add(background); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } Code related to event handling

public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }

Review Java provides two sets of facilities for developing GUIs: –The Abstract Window Toolkit (AWT): package java.awt –Swing: package javax.swing Event-driven

Event Handling Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. : Act that results in the event Listener type: User clicks a button, presses Return while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window) WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener

Button Event javax.swing.AbstractButton javax.swing.JButton addActionListener(ActionListener a) SWING ActionListener AWT actionPerformed(ActionEvent e) (When an ActionEvent occurs, a component notifies its registered ActionListener objects by invoking their actionPerformed methods) (All abstract methods and classes need to be defined)

New Button Event examples First example Improved example

TextField Event example

Panels Container that can hold other components “miniature frame” – no title bar or border Panels can contain other panels Each panel can have its own layout JFrame Top Level Component getContentPane() JFrame

Panels Container that can hold other components “miniature frame” – no title bar or border Panels can contain other panels Each panel can have its own layout JPanel (background) One main panel getContentPane.add()

Panels Container that can hold other components “miniature frame” – no title bar or border Panels can contain other panels Each panel can have its own layout JPanel More panels for organisation background.add()

Panels Container that can hold other components “miniature frame” – no title bar or border Panels can contain other panels Each panel can have its own layout B B B B JTextArea Atomic components

Arranging components Layout managers are used to control the size and position of components in containers. The Java platform provides a number of layout managers, including BorderLayout, FlowLayout and GridLayout. To use layout mangers, you have to import java.awt.*. To use a particular layout manager, you use the setLayout method.

import javax.swing.*; import java.awt.*; public class TestFlowLayout extends JFrame { private JButton button1 = new JButton("One"); private JButton button2 = new JButton("Two"); private JButton button3 = new JButton("Three"); private JButton button4 = new JButton("Four"); private JPanel background = new JPanel(); public TestFlowLayout() { background.setLayout(new FlowLayout()); background.add(button1); background.add(button2); background.add(button3); background.add(button4); getContentPane().add(background); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } FlowLayout manager: Buttons are positioned from left to right as they are added. If you resize the window, the buttons are not resized.

import javax.swing.*; import java.awt.*; public class TestBorderLayout extends JFrame { private JButton buttonN = new JButton("North"); private JButton buttonS = new JButton("South"); private JButton buttonE = new JButton("East"); private JButton buttonW = new JButton("West"); private JButton buttonC = new JButton("Center"); private JPanel background = new JPanel(); public TestBorderLayout() { background.setLayout(new BorderLayout()); background.add(buttonN, BorderLayout.NORTH); background.add(buttonS, BorderLayout.SOUTH); background.add(buttonE, BorderLayout.EAST); background.add(buttonW, BorderLayout.WEST); background.add(buttonC, BorderLayout.CENTER); getContentPane().add(background); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } BorderLayout manager: When we add components, we specify a particular position. Not suitable for buttons, but is useful for positioning panels of components.

How BorderLayout resizes The size of the buttons change to fill up the entire area of the window. Note: you do not have to fill all areas in a BorderLayout

PackedFrame example

Component Hierarchy JButton button1 PackedFrame : (contentPane) JPanel (panelTwo) JPanel (background) JPanel (panelOne) JButton button2 JButton button6 JButton button5 JButton button4 JButton button7 JButton button8 JButton button3 FlowLayoutBorderLayout

History: Charles Babbage eccentric British mathematician and inventor Difference Engine Analytical Engine –Automatic arithmetic calculations carried out with punch cards –Machine memory –Rods, cylinders, gears, bells for 10 digit number system Never completed –More than 150 years later, a Difference Engine was eventually constructed from original drawings by a team at London's Science Museum. –The final machine consisted of 4,000 components, weighed three tons, and was 10 feet wide and 6½ feet tall. –The device returned results to 31 digits of accuracy.