Java Swing Overview A.O’Riordan, Nov., 2007 Includes notes by K. Brown, 2004-2007.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Introduction to Java 2 Programming
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.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
User Interface Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Introduction to JFC Swing Written by Adam Carmi. Agenda About JFC and Swing Pluggable Look and Feel Swing Components Borders Layout Management Events.
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
Advanced Java Class GUI – part 1. Intro to GUI GUI = Graphical User Interface -- “Gooey” Just because it’s “gooey” does not mean you may write messy code.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Introduction to Java Swing “We are the sultans of swing” – Mark Knopfler.
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
GUI Programming in Java
Draw Shapes Introduction to simple graphics. What is a Component? A class that resides in the java.awt package Examples include: –Button, java.awt.Button.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
Java Swing, Events and MVC Optional Readings: Eckel’s Thinking in Java: Chap 14 (
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
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.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
3461A Readings from the Swing Tutorial. 3461A Overview  The follow is the Table of Contents from the trail “Creating a GUI with JFC/Swing” in the “The.
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.
Dale Roberts GUI Programming using Java - Introduction Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
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.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
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.
Java Programming: Advanced Topics 1 Components and Facilities for Rich Graphical User Interfaces Chapter 7.
1 Java Swing - Lecture 2 Components and Containment Boriana Koleva
CSCI Swing1 The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness –The Abstract.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
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.
UID – Event Handling and Listeners Boriana Koleva
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Swing - 2 Session 13. Swing - 2 / 2 of 38 Objectives (1) Discuss trees and tables Discuss progress bars Discuss MVC architecture Describe menus.
5-Jan-16 R Ramesh Swing. 5-Jan-16 R Ramesh An Introduction to Java Foundation Classes (JFC) A suite of libraries to assist programmers create enterprise.
Java Swing One of the most important features of Java is its ability to draw graphics.
Lecture # 6 Graphical User Interface(GUI). Introduction A graphical user interface (GUI) presents a user- friendly mechanism for interacting with an application.
Java Swing, Events Readings: Just Java 2: Chap 19 & 21, or Eckel’s Thinking in Java: Chap 14 Slide credits to CMPUT 301, Department of Computing Science.
Event Handling and Listeners in SWING The practice of event handling.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Introduction to Swing Mr. Crone. What is Swing? a collection of pre-made Java classes used to create a modern graphical user interface.
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:
Module 13: Swing API Object Oriented Programming(Java)
A Quick Java Swing Tutorial
Welcome To java
A First Look at GUI Applications
University of Central Florida COP 3330 Object Oriented Programming
A Quick Java Swing Tutorial
Introduction to Computing Using Java
A Quick Java Swing Tutorial
Introduction to Graphical Interfaces in Java: AWT and Swing
Presentation transcript:

Java Swing Overview A.O’Riordan, Nov., 2007 Includes notes by K. Brown,

What is Swing? Swing widget toolkit for Java used for constructing a graphical user interface (GUI) - part of The Java Foundation Classes (JFC) “Swing” was the codename of the project that developed the first JFC components Swing improvement on earlier Abstract Window Toolkit (AWT) AWT includes basic set of GUI widgets such as buttons, text boxes, and menus, several layout managers, core GUI event subsystem, and AWT Native Interface JFC includes Pluggable Look and Feel; Accessibility; Java 2D (Java 2 onwards); Drag and Drop

Swing Characteristics Platform independent Extensible Component based Customizable Event driven Separates Component Model from View Lightweight Demo – WebStart SwingSet –

Swing History 1996AWT part of Java from start 1997Sun incorporates Netscape Communications's IFC (Internet Foundation Classes) with other technologies to form the Java Foundation Classes. 1998Released as part of the Java Standard Edition release Drag and drop added (release 1.4) 2004/6Improvements in Java 5 and 6 Much of the Swing API is generally a extension of the AWT rather than a direct replacement At its core, every Swing component relies on an AWT container, since (Swing's) JComponent extends (AWT's) Container

Swing Structure Swing is large - learn general principles and design styles - then use the API reference Java 6 API Reference available at: – Sun’s Swing tutorial – Swing, like the rest of the Java API, is subdivided into packages: –javax.swing –javax.accessibility –javax.swing.border … Most Swing programs also need AWT packages –java.awt –java.awt.event

Swing Overview Swing applications consists of multiple parts –Containers –Components –Events –Graphics Sun makes a distinction between lightweight and heavyweight components: –Lightweight components are not dependent on native peers to render themselves. They are coded in Java. –Heavyweight components are rendered by the host operating system. They are managed by the underlying window manager.

Top-level Containers At the root of every containment hierarchy All Swing programs have at least one Content panes - contains everything except menu bar for most Swing applications Types of top-level containers: JFrame - Window with border, title and buttons Dialogs – secondary window –More limited than frames –Types of dialogs – JOptionPane, ProgressMonitor, JColorChooser, JDialog JApplet – requires Java plug-in for browser

Panels/Panes – Intermediate-level Containers I You don’t add (atomic) components such as buttons directly onto a top-level container such as a JFrame. Each top-level container has a content pane that contains visible components in that top-level container’s GUI. Add component to the content pane: JFrame frame = new JFrame("HelloWorld App"); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label);

Panels/Panes – Intermediate-level Containers II JPanel Simplify the positioning of other components Contains everything except menu bar for most Swing applications A panel’s default layout manager is FlowLayout Create as a separate class: MyPanel panel = new MyPanel(); frame.getContentPane().add(panel); JScrollPane; JTabbedPane Allow interaction

Create a Component Created just like any class instance –JButton button_ok = new JButton(“OK”); Range in complexity from very simple (e.g. JButton) to very detailed (e.g. JColorChooser) With an image: ImageIcon cup = new ImageIcon("images/cup.gif"); JButton button1 = new JButton("Java", cup);

Some Types of Component Buttons Combo boxes Lists Menus Sliders Text Fields Labels

More Components Tool tips Progress bars Colour choosers File choosers Tables Text Trees

Basic Swing Components

Swing Component Hierarchy (image from here:

Methods inherited by components … customising appearance –get/set Border/Font/Background... affecting component state –enabling, making visible,... registering listeners displaying the component ("painting") adding and removing other components determining layout –get/set Layout/PreferredSize... absolute positioning –get/set Size/Location/Bounds...

Using a Component 1.Create it 2.Configure it 3.Add children (if container) 4.Add to parent (if not JFrame) 5.Listen to it Event handling and listeners - three key bits of code: 1) add interface 2) register 3) handle Components can have multiple listeners

Container (window) with component (button) All this for one button click... user user clicks button event object is generated ae:ActionEvent event is queued for action Listener objects... do something event dispatch loop: remove from queue, invoke handlers in registered listeners

Types of Events AWT Event Hierarchy (from :

EventObject’s Methods Events are represented as Objects Superclass of all event classes is java.util.EventObject Methods defined in EventObject class : Object getSource() returns the object that originated the event - if the user clickes a button, the method getSource returns the object corresponding to button int getID() returns the integer value corresponding to the type of event - e.g. if the user clickes mouse, method getID returns the integer defined as MouseEvent.MOUSE_CLICKED

Component Listeners Global component listeners may be used for any components ComponentListener (changes in size, position, visibility) FocusListener (whether ability for keyboard input) KeyListener (key press events, only with focus) MouseListener (clicks and movement into/out of component area) MouseMotionListener (changes in position over component) Component-specific listeners relevant to specific components ActionListener, CaretListener, ChangeListener, DocumentListener, ItemListener, ListSelectionListener, WindowListener, etc.

Example: WindowListener the WindowListener interface specifies methods which respond to changes in a window's state: windowActivated(...) : window is set to be active windowClosed(...) : window is closed by program windowClosing(...) : window closed by user windowDeactivated(...) : window is no longer active windowDeiconified(...) : window is restored to normal windowIconified(...) : window is minimised windowOpened(...) : window opened for first time

Listener as Inner Class Listener as Inner Class (what we’ve done in all the examples so far) public class Gui{ public static void main(String[] args) { JFrame frame = new JFrame(); frame.addWindowListener(new MyWinListener()); //... private class MyWinListener extends WindowListener { public void windowClosing(WindowEvent we) { System.exit(0); } // etc.

Anonymous Inner Class Listener as Anonymous Inner Class –No class name frame.addWindowListener(new WindowListener(){ public void windowClosing(WindowEvent we) { System.exit(0); } //etc. } // end class definition

GUI itself implementing Listener GUI implements listener itself: public class Gui implements WindowListener{ public static void main(String[] args) { JFrame frame = new JFrame(); frame.addWindowListener(this); //... public void windowClosing(WindowEvent we) { System.exit(0); } // etc.

Pluggable Look and Feel (PLAF) Import package javax.swing.plaf Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities Can use third party PLAF or create your own look and feel using the Synth package Here are some utility functions that set the LAF to native, Java (Metal), and Motif, respectively: UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

Look and Feel Example Examples: Java, Windows, Motif respectively:

Graphics class Java AWT Graphics - basic but usually enough Properties stored in Graphics object - Color, Font, etc Methods of Graphics can: Draw shapes - lines, rectangles, 3D rectangles, round-edged rectangles, ovals, arcs, polygons, e.g. –drawImage; drawLine; drawOval; drawArc; drawRect –fillArc; fillOval; fillRect Set or get properties, e.g. –setColor; setFont –getColor; getFont Draw text - Draw string on screen as a graphic –drawString

Java2D Java2D graphics: Extends the AWT graphics to provide much more, e.g. gradients, textures, etc. (package java.awt.Graphics2D ) Graphics2D class extends the Graphics class richer graphics, font, and image APIs enhanced colour definition and composition, hit detection on arbitrary geometric shapes and text, and a uniform rendering model for printers and display devices

Painting Components Each JComponent has method for drawing components: void paintComponent(Graphics g) Every component in a GUI has an object of the class Graphics associated with it known as the graphics context. It holds info about the current output device (e.g. the screen), the current drawing colour, the current font, and the clip rectangle (i.e. the area that needs repainting). Whenever the system invokes a component's paint method, it supplies the component's graphics context as a parameter.

When is a component painted? System-triggered painting: the system requests painting: when a component is first made visible when a component is resized by the user when a component has been damaged and needs repair Application-triggered painting : when a component's model is updated Call repaint() method - paints whole component & any others as needed repaint(int leftx,int lefty,int width,int height) - only repaints a specified area Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched.

Custom painting define a subclass of some JComponent (e.g. a subclass of JPanel) in your class definition, override paintComponent always have the following as the first line in your definition of paintComponent super.paintComponent(g); send messages to g, the graphics context, to get it to draw things for you

Swing not covered Lots more components –JInternalFrame,.JDesktopIcon, JLayeredPane, JMenuBar,, JPopupMenu, JProgressBar, JRootPane, JScrollBar, JScrollPane, JSeparator, JSpinner, JSplitPane, JTabbedPane, JTable, JTableHeader, JTextComponent, JToolBar, JToolTip, JTree, JViewportJInternalFrame.JDesktopIconJLayeredPaneJMenuBarJPopupMenu JProgressBarJRootPaneJScrollBarJScrollPaneJSeparatorJSpinner JSplitPaneJTabbedPaneJTableJTableHeaderJTextComponentJToolBar JToolTipJTreeJViewport Swing Models - specify how the data and state of a Swing component are stored and retrieved Borders Threaded Applications Assistive Technology – support for voice interfaces, screen readers Internationalization and Localization Integrate with Desktop Focus Subsystem Key bindings Dialog Modality Printing Drag and Drop Undo Framework