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