Swing: Building GUIs in Java

Similar documents
Swing: Building GUIs in Java

Graphical User Interfaces (GUIs)

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

CS 251 Intermediate Programming More on classes

Packages Inner Classes

EPITA Première Année Cycle Ingénieur. Atelier Java - J5

Swing from A to Z Using Focus in Swing, Part 2. Preface

CS108, Stanford Handout #22. Thread 3 GUI

Topic 6: Inner Classes

enum Types 1 1 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 267 / 287

Swing from A to Z Some Simple Components. Preface

Interfaces. An interface forms a contract between the object and the outside world.

Part I: Learn Common Graphics Components

CS 251 Intermediate Programming GUIs: Event Listeners

Another IS-A Relationship

Graphical interfaces & event-driven programming

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Java Swing Introduction

Timing for Interfaces and Abstract Classes

C30b: Inner Class, Anonymous Class, and Lambda Expression

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.

*An nested class is a class that is defined inside another class.

Introduction to concurrency and GUIs

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

CS 11 java track: lecture 3

Final Exam CS 251, Intermediate Programming December 13, 2017

Graphical User Interface (GUI)

AP CS Unit 11: Graphics and Events

(Incomplete) History of GUIs

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Graphical User Interface (GUI)

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

CS11 Java. Fall Lecture 4

CPS221 Lecture: Threads

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Interfaces (1/2) An interface forms a contract between the object and the outside world.

CS Exam 1 Review Suggestions

CITS2210 Object-Oriented Programming. Topic 10. Java: Nested and Inner Classes

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

Widget Toolkits CS MVC

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

User Interface Programming OOP/Java Primer. Step 4 Some Final Checkups

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Programming Language Concepts: Lecture 8

Swing. By Iqtidar Ali

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Graphical User Interface (GUI)

Object-Oriented Programming Design. Topic : Graphics Programming GUI Part I

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

CS193j, Stanford Handout #21. Threading 3

Widgets. Widgets Widget Toolkits. User Interface Widget

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY

Example: CharCheck. That s It??! What do you imagine happens after main() finishes?

Introduction to the JAVA UI classes Advanced HCI IAT351

SD Module-1 Advanced JAVA

Lecture 5: Java Graphics

Coverage of Part 2. A Brief Introduction to Java for C++ Programmers: Part 2. import: using packages

SD Module-1 Advanced JAVA. Assignment No. 4

Basicsof. JavaGUI and SWING

Lecture 3: Java Graphics & Events

Programming Languages and Techniques (CIS120)

Design Patterns: Part 2

MODEL UPDATES MANIPULATES USER

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Subtype Polymorphism

Java Thread Programming By Paul Hyde

CSE 331 Software Design & Implementation

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Sketchpad. Plan for Today. Class 22: Graphical User Interfaces IBM 705 (1954) Computer as Clerk : Augmenting Human Intellect

CS 251 Intermediate Programming GUIs: Components and Layout

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

CS11 Java. Fall Lecture 3

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

CS415 Human Computer Interaction

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

GUI Programming. Chapter. A Fresh Graduate s Guide to Software Development Tools and Technologies

Object-oriented programming in Java (2)

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

CSC207 Week 4. Larry Zhang

Reflection. Based on

Java Concurrency in practice Chapter 9 GUI Applications

Java, Swing, and Eclipse: The Calculator Lab.

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

FirstSwingFrame.java Page 1 of 1

GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

Java: Graphical User Interfaces (GUI)

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Model-View-Controller

Widget. Widget is a generic name for parts of an interface that have their own behaviour. e.g., buttons, progress bars, sliders, drop-down

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Window Interfaces Using Swing Objects

Transcription:

Swing: Building GUIs in Java ENGI 5895: Software Design Andrew Vardy Faculty of Engineering & Applied Science Memorial University of Newfoundland February 13, 2017

Outline 1 Introduction 2 Aside: Inner Classes 3 Aside: Threads 4 Examples

Introduction Swing is an officially supported GUI toolkit for Java. It was developed to replace the GUI components of the Abstract Window Toolkit (AWT). It has the following features:

Introduction Swing is an officially supported GUI toolkit for Java. It was developed to replace the GUI components of the Abstract Window Toolkit (AWT). It has the following features: Pluggable look and feel [DEMO]

Introduction Swing is an officially supported GUI toolkit for Java. It was developed to replace the GUI components of the Abstract Window Toolkit (AWT). It has the following features: Pluggable look and feel [DEMO] Numerous standard and specialized widgets (text boxes, buttons, tabbed panels,...)

Introduction Swing is an officially supported GUI toolkit for Java. It was developed to replace the GUI components of the Abstract Window Toolkit (AWT). It has the following features: Pluggable look and feel [DEMO] Numerous standard and specialized widgets (text boxes, buttons, tabbed panels,...) Swing components render themselves in an OS-independent manner

Introduction Swing is an officially supported GUI toolkit for Java. It was developed to replace the GUI components of the Abstract Window Toolkit (AWT). It has the following features: Pluggable look and feel [DEMO] Numerous standard and specialized widgets (text boxes, buttons, tabbed panels,...) Swing components render themselves in an OS-independent manner Relative layout of components

Introduction Swing is an officially supported GUI toolkit for Java. It was developed to replace the GUI components of the Abstract Window Toolkit (AWT). It has the following features: Pluggable look and feel [DEMO] Numerous standard and specialized widgets (text boxes, buttons, tabbed panels,...) Swing components render themselves in an OS-independent manner Relative layout of components Nice design choices: Easily extensible with heavy use of patterns

Packages In the past the AWT provided the widgets, but it is generally advisable to use only Swing widgets. However, much of the functionality provided by AWT has been retained by Swing: java.awt: Contains superclasses for GUI components, as well as other useful classes such as Color and Point

Packages In the past the AWT provided the widgets, but it is generally advisable to use only Swing widgets. However, much of the functionality provided by AWT has been retained by Swing: java.awt: Contains superclasses for GUI components, as well as other useful classes such as Color and Point java.awt.event: Classes for event handling

Packages In the past the AWT provided the widgets, but it is generally advisable to use only Swing widgets. However, much of the functionality provided by AWT has been retained by Swing: java.awt: Contains superclasses for GUI components, as well as other useful classes such as Color and Point java.awt.event: Classes for event handling javax.swing: Contains the actual GUI components

Packages In the past the AWT provided the widgets, but it is generally advisable to use only Swing widgets. However, much of the functionality provided by AWT has been retained by Swing: java.awt: Contains superclasses for GUI components, as well as other useful classes such as Color and Point java.awt.event: Classes for event handling javax.swing: Contains the actual GUI components

Packages In the past the AWT provided the widgets, but it is generally advisable to use only Swing widgets. However, much of the functionality provided by AWT has been retained by Swing: java.awt: Contains superclasses for GUI components, as well as other useful classes such as Color and Point java.awt.event: Classes for event handling javax.swing: Contains the actual GUI components The Swing components all start with J. e.g. JButton, JPanel, JFrame... Avoid the non-j versions of these.

Class Diagram This is a partial class diagram for AWT and Swing: In orange are the commonly used containers for other components. In blue are some of the commonly used components. What design patterns do you see here?

Aside: Inner Classes You can create classes within classes. These are known as Inner Classes. Why would you want anything so strange?

Aside: Inner Classes You can create classes within classes. These are known as Inner Classes. Why would you want anything so strange? Like helper methods you can create helper classes which are embedded within a larger class

Aside: Inner Classes You can create classes within classes. These are known as Inner Classes. Why would you want anything so strange? Like helper methods you can create helper classes which are embedded within a larger class Inner classes have priviledged access to private members of the outer class

Aside: Inner Classes You can create classes within classes. These are known as Inner Classes. Why would you want anything so strange? Like helper methods you can create helper classes which are embedded within a larger class Inner classes have priviledged access to private members of the outer class Similar to the friend feature of C++, only more contained

Aside: Inner Classes You can create classes within classes. These are known as Inner Classes. Why would you want anything so strange? Like helper methods you can create helper classes which are embedded within a larger class Inner classes have priviledged access to private members of the outer class Similar to the friend feature of C++, only more contained Having small classes declared close to their point of use helps readibility and maintainability

Life of an Inner Class Each inner class instance is associated with an outer class instance. Consider this example: class Outer { private int outvalue = 6; public int getvalue () { return outvalue ;

Life of an Inner Class Each inner class instance is associated with an outer class instance. Consider this example: class Outer { private int outvalue = 6; public int getvalue () { return outvalue ; class Inner1 { private int value ;

Life of an Inner Class Each inner class instance is associated with an outer class instance. Consider this example: class Outer { private int outvalue = 6; public int getvalue () { return outvalue ; class Inner1 { private int value ; Inner1 () { value = outvalue + 1;

Life of an Inner Class Each inner class instance is associated with an outer class instance. Consider this example: class Outer { private int outvalue = 6; public int getvalue () { return outvalue ; class Inner1 { private int value ; Inner1 () { value = outvalue + 1; public int getvalue () { return value ;

To create an instance of an inner class within the outer class, the syntax is straightforward: class Outer2 { int outvalue = 14; Outer2 () { Inner2 inner2 = new Inner2 ();

To create an instance of an inner class within the outer class, the syntax is straightforward: class Outer2 { int outvalue = 14; Outer2 () { Inner2 inner2 = new Inner2 (); class Inner2 { Inner2 () { outvalue++;

To create an instance of an inner class within the outer class, the syntax is straightforward: class Outer2 { int outvalue = 14; Outer2 () { Inner2 inner2 = new Inner2 (); class Inner2 { Inner2 () { outvalue++; public class TestOuter2 { public static void main( String [] args) { Outer2 outer2 = new Outer2 (); System. out. println( outer2. outvalue );

To create an instance of an inner class within the outer class, the syntax is straightforward: class Outer2 { int outvalue = 14; Outer2 () { Inner2 inner2 = new Inner2 (); class Inner2 { Inner2 () { outvalue++; public class TestOuter2 { public static void main( String [] args) { Outer2 outer2 = new Outer2 (); System. out. println( outer2. outvalue );

We can also create instances of an inner class from OUTSIDE the outer class, but the syntax is weird: OuterClass. InnerClass innerobject = outerobject. new InnerClass ();

We can also create instances of an inner class from OUTSIDE the outer class, but the syntax is weird: OuterClass. InnerClass innerobject = outerobject. new InnerClass (); Notice how new is treated like a field of the outer class. Here we test our previous example:

We can also create instances of an inner class from OUTSIDE the outer class, but the syntax is weird: OuterClass. InnerClass innerobject = outerobject. new InnerClass (); Notice how new is treated like a field of the outer class. Here we test our previous example: public class TestOuter { public static void main( String [] args) { Outer outer = new Outer (); System. out. println( outer. getvalue ());

We can also create instances of an inner class from OUTSIDE the outer class, but the syntax is weird: OuterClass. InnerClass innerobject = outerobject. new InnerClass (); Notice how new is treated like a field of the outer class. Here we test our previous example: public class TestOuter { public static void main( String [] args) { Outer outer = new Outer (); System. out. println( outer. getvalue ()); Outer. Inner1 inner = outer. new Inner1 (); System. out. println( inner. getvalue ());

Nested Classes The general category to which inner classes belong is nested classes. There are two types of nested classes: inner classes (as we have seen) and static nested classes. A static nested class is like an inner class but does not have access to the members of the enclosing class:

Nested Classes The general category to which inner classes belong is nested classes. There are two types of nested classes: inner classes (as we have seen) and static nested classes. A static nested class is like an inner class but does not have access to the members of the enclosing class: class OuterClass {... static class StaticNestedClass {... class InnerClass {...

Nested Classes The general category to which inner classes belong is nested classes. There are two types of nested classes: inner classes (as we have seen) and static nested classes. A static nested class is like an inner class but does not have access to the members of the enclosing class: class OuterClass {... static class StaticNestedClass {... class InnerClass {... Example from The Java Tutorials: http:download.oracle. com/javase/tutorial/java/javaoo/nested.html Static nested classes are basically top-level classes that are packaged within another class for convenience.

Local Classes Alocalclassisanestedclassdeclaredwithinthebodyofa method. Note that it still has access to outer class members: import java. util. ; class Celebrity extends Observable { / /

Local Classes Alocalclassisanestedclassdeclaredwithinthebodyofa method. Note that it still has access to outer class members: import java. util. ; class Celebrity extends Observable { / / class MyOuter1 { int i = 0; public void dostuff () { Celebrity britney = new Celebrity ();

Local Classes Alocalclassisanestedclassdeclaredwithinthebodyofa method. Note that it still has access to outer class members: import java. util. ; class Celebrity extends Observable { / / class MyOuter1 { int i = 0; public void dostuff () { Celebrity britney = new Celebrity (); Declare a local class as an Oberver class MyLocalObserver implements Observer { public void update( Observable o, Object arg) {... i++;

Local Classes Alocalclassisanestedclassdeclaredwithinthebodyofa method. Note that it still has access to outer class members: import java. util. ; class Celebrity extends Observable { / / class MyOuter1 { int i = 0; public void dostuff () { Celebrity britney = new Celebrity (); Declare a local class as an Oberver class MyLocalObserver implements Observer { public void update( Observable o, Object arg) {... i++; britney. addobserver( new MyLocalObserver () );

Anonymous Classes Anonymous classes can be declared and instantiated at the same time. Note that they still have access to outer class members: import java. util. ; class Celebrity extends Observable { / /

Anonymous Classes Anonymous classes can be declared and instantiated at the same time. Note that they still have access to outer class members: import java. util. ; class Celebrity extends Observable { / / class MyOuter2 { int i = 0;

Anonymous Classes Anonymous classes can be declared and instantiated at the same time. Note that they still have access to outer class members: import java. util. ; class Celebrity extends Observable { / / class MyOuter2 { int i = 0; public void dostuff () { Celebrity britney = new Celebrity ();

Anonymous Classes Anonymous classes can be declared and instantiated at the same time. Note that they still have access to outer class members: import java. util. ; class Celebrity extends Observable { / / class MyOuter2 { int i = 0; public void dostuff () { Celebrity britney = new Celebrity (); Create an anonymous inner class and add as an observer of britney. britney. addobserver( new Observer () { public void update( Observable o, Object arg) {... i++; );

Aside: Threads A process is a self contained program with its own resources. A thread is a lightweight process. Threads share the memory space of the process that spawned them.

Aside: Threads A process is a self contained program with its own resources. A thread is a lightweight process. Threads share the memory space of the process that spawned them. Aprocesswithmultiplethreadsisusefulinsituationswherevarious clients (e.g. the user, network connections) must be continually addressed. However, they introduce a number of potential problems. Concurrency is a big topic (the subject of a whole course 8893). In this course you are advised to follow the guidelines for using threads in Swing. If you are sure your project needs multiple threads, read the following tutorial:

Aside: Threads A process is a self contained program with its own resources. A thread is a lightweight process. Threads share the memory space of the process that spawned them. Aprocesswithmultiplethreadsisusefulinsituationswherevarious clients (e.g. the user, network connections) must be continually addressed. However, they introduce a number of potential problems. Concurrency is a big topic (the subject of a whole course 8893). In this course you are advised to follow the guidelines for using threads in Swing. If you are sure your project needs multiple threads, read the following tutorial: http:download.oracle.com/javase/tutorial/essential/ concurrency/index.html

Guideline for Threads in Swing Swing is not thread-safe. Willy-nilly usage of threads will create problems! Possible problems range from unresponsive user interfaces to bizarre crashes and exceptions.

Guideline for Threads in Swing Swing is not thread-safe. Willy-nilly usage of threads will create problems! Possible problems range from unresponsive user interfaces to bizarre crashes and exceptions. There are three types of threads to be concerned with:

Guideline for Threads in Swing Swing is not thread-safe. Willy-nilly usage of threads will create problems! Possible problems range from unresponsive user interfaces to bizarre crashes and exceptions. There are three types of threads to be concerned with: Initial thread(s): Executes the initial code of your application

Guideline for Threads in Swing Swing is not thread-safe. Willy-nilly usage of threads will create problems! Possible problems range from unresponsive user interfaces to bizarre crashes and exceptions. There are three types of threads to be concerned with: Initial thread(s): Executes the initial code of your application The event dispatch thread: Handlesallevents.Almostallof your Swing code will run in this thread. Computationally expensive tasks should not be executed here.

Guideline for Threads in Swing Swing is not thread-safe. Willy-nilly usage of threads will create problems! Possible problems range from unresponsive user interfaces to bizarre crashes and exceptions. There are three types of threads to be concerned with: Initial thread(s): Executes the initial code of your application The event dispatch thread: Handlesallevents.Almostallof your Swing code will run in this thread. Computationally expensive tasks should not be executed here. Worker or background threads: Handle expensive tasks running in the background.

The most important rule is that Swing code should almost always should be executed in the event-dispatch thread. The code in main can be considered the initial thread. In Swing applications the main job of the initial thread is to create a Runnable object and schedule it for execution on the event dispatch thread.

The most important rule is that Swing code should almost always should be executed in the event-dispatch thread. The code in main can be considered the initial thread. In Swing applications the main job of the initial thread is to create a Runnable object and schedule it for execution on the event dispatch thread. Runnable is an interface that consists of nothing but public void run(). The Runnable created should be passed to SwingUtilities.invokeLater or SwingUtilities.invokeAndWait. In the following, we create an anonymous Runnable class and call invokelater on it:

The most important rule is that Swing code should almost always should be executed in the event-dispatch thread. The code in main can be considered the initial thread. In Swing applications the main job of the initial thread is to create a Runnable object and schedule it for execution on the event dispatch thread. Runnable is an interface that consists of nothing but public void run(). The Runnable created should be passed to SwingUtilities.invokeLater or SwingUtilities.invokeAndWait. In the following, we create an anonymous Runnable class and call invokelater on it: SwingUtilities. invokelater( new Runnable () { public void run () { createandshowgui (); );

The most important rule is that Swing code should almost always should be executed in the event-dispatch thread. The code in main can be considered the initial thread. In Swing applications the main job of the initial thread is to create a Runnable object and schedule it for execution on the event dispatch thread. Runnable is an interface that consists of nothing but public void run(). The Runnable created should be passed to SwingUtilities.invokeLater or SwingUtilities.invokeAndWait. In the following, we create an anonymous Runnable class and call invokelater on it: SwingUtilities. invokelater( new Runnable () { public void run () { createandshowgui (); ); For more details see the Java tutorial on Concurrency in Swing : http:download.oracle.com/javase/tutorial/uiswing/ concurrency/index.html

Examples Code for the following examples will be posted on the course website. FirstSwingFrame SecondSwingFrame LayoutPlay Paint1 Paint2 GameOfLife