Java for Interfaces and Networks (DT3010, HT10)

Similar documents
Java for Interfaces and Networks (DT3029)

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY

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

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

Java for Interfaces and Networks (DT3010, HT10)

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

MIT AITI Swing Event Model Lecture 17

CS108, Stanford Handout #22. Thread 3 GUI

Points Missed on Page page 1 of 8

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Graphic User Interfaces. - GUI concepts - Swing - AWT

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

AP CS Unit 11: Graphics and Events

Graphical User Interfaces. Comp 152

Lecture 5: Java Graphics

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Part I: Learn Common Graphics Components

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

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Window Interfaces Using Swing Objects

Agenda. Container and Component

Midterm assessment - MAKEUP Fall 2010

Window Interfaces Using Swing Objects

Graphic Interface Programming II Events and Threads. Uppsala universitet

Graphical User Interface (GUI)

Java for Interfaces and Networks

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

Introduction. Introduction

Java for Interfaces and Networks (DT3010, HT10)

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

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

G51PRG: Introduction to Programming Second semester Applets and graphics

CS 251 Intermediate Programming GUIs: Event Listeners

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CS193j, Stanford Handout #21. Threading 3

User interfaces and Swing

Lecture 3: Java Graphics & Events

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!

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

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

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Question 1. Show the steps that are involved in sorting the string SORTME using the quicksort algorithm given below.

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Swing from A to Z Some Simple Components. Preface

Java Programming Lecture 6

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Window Interfaces Using Swing. Chapter 12

Graphical User Interfaces (GUIs)

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Java for Interfaces and Networks (DT3029)

Graphical interfaces & event-driven programming

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

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

Programming graphics

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

INTRODUCTION TO (GUIS)

Introduction to concurrency and GUIs

Java: Graphical User Interfaces (GUI)

We are on the GUI fast track path

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

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

Jonathan Aldrich Charlie Garrod

Graphical User Interface (GUI)

Class 16: The Swing Event Model

H212 Introduction to Software Systems Honors

Example: Building a Java GUI

Example: Building a Java GUI

Introduction to the JAVA UI classes Advanced HCI IAT351

Implementing Graphical User Interfaces

Assignment 2. Application Development

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Graphical User Interfaces in Java - SWING

Class 34: Introduction to Threads

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

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CS193k, Stanford Handout #10. Threads 4 / RMI

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

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

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2012

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Packages: Putting Classes Together

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Programming Languages and Techniques (CIS120e)

AnimatedImage.java. Page 1

PIC 20A GUI with swing

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Transcription:

Java for Interfaces and Networks (DT3010, HT10) More on Swing and Threads Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks Lecture 10 1 / 29

Outline 1 Scheduling Application Code on Event Threads 2 Worker Threads 3 Creating Your Own Swing Components Federico Pecora Java for Interfaces and Networks Lecture 10 2 / 29

Scheduling Application Code on Event Threads Outline 1 Scheduling Application Code on Event Threads 2 Worker Threads 3 Creating Your Own Swing Components Federico Pecora Java for Interfaces and Networks Lecture 10 3 / 29

Scheduling Application Code on Event Threads Synchronization in Swing Every program has a set of initial threads where the application logic begins In standard programs, there is only one: the thread that invokes main() In applets these threads construct the applet object and invoke its init() and start() methods these actions may occur on one or several threads, depending on the JVM implementation In Swing programs, initial threads create a Runnable object that initializes the GUI Once the GUI is created, the program is primarily driven by GUI events Federico Pecora Java for Interfaces and Networks Lecture 10 4 / 29

Scheduling Application Code on Event Threads Swing event dispatch thread GUI events are performed by a special Swing thread known as the event dispatch thread takes an ActionEvent off the queue and processes it essentially, the event dispatch thread is running the actionperformed() methods The event dispatch thread can actually be implemented as one or more threads Application code can schedule additional tasks on the event dispatch thread e.g., update a text field as a result of something other than an ActionEvent Federico Pecora Java for Interfaces and Networks Lecture 10 5 / 29

Scheduling Application Code on Event Threads Example: how not to do it We add a non-editable JTextField to our chat client (see lecture 8) showing the latest message ClientWithButtons.java 1 public class ClientWithButtons { 2 //... 3 private JTextField outputfield; 4 private class ServerListener extends Thread { 5 public void run() { 6 String linefromserver; 7 try { 8 while ((linefromserver = in.readline())!= null && 9!lineFromServer.equals("quit")) { 10 System.out.println("From server: " + linefromserver); 11 outputfield.settext(linefromserver); 12 } 13 } catch (IOException e) {... } 14 } //class ServerListener 15 //... Federico Pecora Java for Interfaces and Networks Lecture 10 6 / 29

Scheduling Application Code on Event Threads Example: how not to do it We add a non-editable JTextField to our chat client (see lecture 8) showing the latest message ClientWithButtons.java (cont.) 25 //... 26 private class ChatButtonWindow extends JFrame { 27 public ChatButtonWindow() { 28 super("extra chat buttons"); 29 Container cp = getcontentpane(); 30 //... 31 outputfield = new JTextField(30); 32 outputfield.seteditable(false); 33 cp.add(outputfield); 34 setsize(600, 200); 35 setvisible(true); 36 } 37 } //class ChatButtonWindow 38 //... Federico Pecora Java for Interfaces and Networks Lecture 10 6 / 29

Scheduling Application Code on Event Threads Example: how not to do it We add a non-editable JTextField to our chat client (see lecture 8) showing the latest message Federico Pecora Java for Interfaces and Networks Lecture 10 6 / 29

Scheduling Application Code on Event Threads Example: how not to do it We add a non-editable JTextField to our chat client (see lecture 8) showing the latest message Notice that two threads are accessing the JTextField the ServerListener thread the event dispatch thread We are guaranteed synchronized access only thanks to the JTextField class This method is thread safe, although most Swing methods are not. [ JTextComponent.setText() API] In general, all GUI components should be manipulated by the event dispatch thread, which guarantees thread safety Federico Pecora Java for Interfaces and Networks Lecture 10 6 / 29

Scheduling Application Code on Event Threads The invokelater() method SwingUtilities.invokeLater(Runnable r) can be run from any thread to request the event dispatching thread to run certain code you specify the code to be run in the run() method of the Runnable object r invokelater() returns immediately, without waiting for the event-dispatching thread to execute the code invokelater() example 1 Runnable updateacomponent = new Runnable() { 2 public void run() { 3 component.dosomething(); 4 } 5 }; 6 SwingUtilities.invokeLater(updateAComponent); Federico Pecora Java for Interfaces and Networks Lecture 10 7 / 29

Scheduling Application Code on Event Threads The invokeandwait() method SwingUtilities.invokeAndWait(Runnable r) identical to invokelater(), except for when it returns...... invokeandwait() does not return until the event-dispatching thread has executed the code invokeandwait() example 1 void showhellotheredialog() throws Exception { 2 Runnable showmodaldialog = new Runnable() { 3 public void run() { 4 JOptionPane.showMessageDialog(myMainFrame, "..."); 5 } 6 }; 7 SwingUtilities.invokeAndWait(showModalDialog); 8 } Federico Pecora Java for Interfaces and Networks Lecture 10 8 / 29

Scheduling Application Code on Event Threads The invokeandwait() method Another example... invokeandwait() example 1 void printtextfield() throws Exception { 2 final String[] mystrings = new String[2]; 3 Runnable gettextfieldtext = new Runnable() { 4 public void run() { 5 for (int i = 0; i < textfields.length; i++) 6 userparameters[i] = textfields[i].gettext(); 7 } 8 }; 9 SwingUtilities.invokeAndWait(getTextFieldText); 10 for (String s : userparameters) 11 System.out.println(s); 12 } Federico Pecora Java for Interfaces and Networks Lecture 10 9 / 29

Scheduling Application Code on Event Threads Chat client using invokelater We add a member Runnable class to manipulate the JTextField ClientWithButtonsNew.java 1 public class ClientWithButtonsNew { 2 //... 3 private JTextField outputfield; 4 private class OutputTextSetter implements Runnable { 5 private String texttoset; 6 public OutputTextSetter(String texttoset) { 7 this.texttoset = texttoset; 8 } 9 public void run() { outputfield.settext(texttoset); } 10 } 11 //... Federico Pecora Java for Interfaces and Networks Lecture 10 10 / 29

Scheduling Application Code on Event Threads Chat client using invokelater We add a member Runnable class to manipulate the JTextField ClientWithButtonsNew.java (cont.) 25 //... 26 private class ServerListener extends Thread { 27 public void run() { 28 String linefromserver; 29 try { 30 while ((linefromserver = in.readline())!= null && 31!lineFromServer.equals("quit")) { 32 System.out.println("From server: " + linefromserver); 33 SwingUtilities.invokeLater( 34 new OutputTextSetter(lineFromServer)); 35 } 36 } catch (IOException e) {... } 37 } //class ServerListener 38 //... Federico Pecora Java for Interfaces and Networks Lecture 10 10 / 29

Scheduling Application Code on Event Threads Calling the event dispatch thread Updating Swing components can be done safely within event listeners they are run by the event dispatch thread Updating Swing components outside an event listener should be done with invokelater() (or invokeandwait()) your code will then be executed by the event dispatch thread N.B.: code passed to invokelater() (as well as event listener code) should execute fast so as to not interfere with event processing! Federico Pecora Java for Interfaces and Networks Lecture 10 11 / 29

Worker Threads Outline 1 Scheduling Application Code on Event Threads 2 Worker Threads 3 Creating Your Own Swing Components Federico Pecora Java for Interfaces and Networks Lecture 10 12 / 29

Worker Threads Multi-threading with worker threads So what if I need to implement GUI-manipulating code that is also computationally demanding? Java SE 6 provides the javax.swing.swingworker class Provides support for implementing worker threads (aka background threads) in Swing applications Useful for, e.g., loading/manipulating images that should be used in the GUI without freezing the GUI Takes care of inter-thread communication SwingWorker is abstract, thus you must provide a concrete subclass Federico Pecora Java for Interfaces and Networks Lecture 10 13 / 29

Worker Threads Multi-threading with worker threads SwingWorker is a generic class, with two parameters types new SwingWorker<T1, T2>() {...} T1 is the return type of the T1 doinbackground() method this method defines what has to be done in the worker thread, and you must implement it T2 specifies a type for intermediate results returned while the background task is still active You can also implement the void done() method, which executes in the event dispatch thread here is where you should update your GUI with the results of the worker thread s doinbackground() Federico Pecora Java for Interfaces and Networks Lecture 10 14 / 29

Worker Threads Multi-threading with worker threads SwingWorker pseudocode 1 class MyWorker extends SwingWorker<Type1, Void> { 2 //This method executed in worker thread 3 public Type1 doinbackground() { 4 Type1 ret; 5 //do something long... 6 //return an object of type Type1 7 return ret; 8 } 9 //This method executed in event dispatch thread 10 public void done() { 11 Type1 result = get(); 12 //use result to update the GUI... 13 } 14 } 15 //... 16 MyWorker worker = new MyWorker(); 17 worker.execute(); Federico Pecora Java for Interfaces and Networks Lecture 10 15 / 29

Worker Threads SwingWorker class: basics The doinbackground() method of the worker thread is started with execute() The execution of a a worker thread can be canceled with cancel(boolean) if false, in-progress tasks are allowed to complete When it completes, the done() method is invoked in the event dispatch thread Federico Pecora Java for Interfaces and Networks Lecture 10 16 / 29

Worker Threads SwingWorker class: basics Access in done() to the result of doinbackground() is provided by the get() method get() returns an object of type Type1 get() throws an InterruptedException if the worker thread was interrupted NB: since done() is executed on the event dispatch thread, it blocks all other events! Federico Pecora Java for Interfaces and Networks Lecture 10 17 / 29

Worker Threads SwingWorker class: example An application that searches for the meaning of life (inspired by Java SE 6 API example) We do not know how long the search will take (but the application could get lucky... ) Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example MeaningOfLife.java 1 public class MeaningOfLife { 2 private JLabel searchlabel = new JLabel(""); 3 private JLabel otherlabel = new JLabel(""); 4 private JButton searchbutton = null; 5 private JButton sthbutton = null; 6 private JButton cancelbutton = null; 7 private MeaningOfLifeSearcher mols = null; 8 //... Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example MeaningOfLife.java (cont.) 9 private class MeaningOfLifeSearcher 10 extends SwingWorker<String, Object> { 11 public String doinbackground() { 12 return findthemeaningoflife(); 13 } 14 private String findthemeaningoflife() { 15 Random rand = 16 new Random(Calendar.getInstance().getTimeInMillis()); 17 String ret = ""; 18 while (true) { 19 if (rand.nextint(100000000) == 42) 20 return "The answer is 42"; 21 } 22 } 23 //... Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example MeaningOfLife.java (cont.) 24 protected void done() { 25 try { searchlabel.settext(get()); } 26 catch (Exception ignore) { 27 searchlabel.settext("search canceled!"); 28 } 29 finally { 30 searchbutton.setenabled(true); 31 cancelbutton.setenabled(false); 32 } 33 } 34 } 35 //... Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example MeaningOfLife.java (cont.) 36 public void creategui() { 37 JFrame f = new JFrame("Find the meaning of life!"); 38 f.setsize(300, 180); 39 Container content = f.getcontentpane(); 40 content.setbackground(color.white); 41 content.setlayout(new FlowLayout()); 42 searchbutton = new JButton( 43 "Search for meaning of life..."); 44 sthbutton = new JButton("Do something else"); 45 cancelbutton = new JButton( 46 "Cancel search for meaning of life!"); 47 cancelbutton.setenabled(false); 48 //add all buttons and labels to content... 49 //... Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example MeaningOfLife.java (cont.) 50 searchbutton.addactionlistener(new ActionListener(){ 51 public void actionperformed(actionevent arg0) { 52 searchlabel.settext("searching..."); 53 searchbutton.setenabled(false); 54 cancelbutton.setenabled(true); 55 mols = new MeaningOfLifeSearcher(); 56 mols.execute(); 57 } 58 }); 59 //... Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example MeaningOfLife.java (cont.) 60 sthbutton.addactionlistener(new ActionListener(){ 61 public void actionperformed(actionevent arg0) { 62 otherlabel.settext( 63 ">> Now GUI is doing something else: " + 64 (int)(math.random()*255) + " <<"); 65 } 66 }); 67 //... Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example MeaningOfLife.java (cont.) 68 cancelbutton.addactionlistener(new ActionListener(){ 69 public void actionperformed(actionevent arg0) { 70 searchbutton.setenabled(true); 71 cancelbutton.setenabled(false); 72 mols.cancel(true); 73 } 74 }); 75 f.setvisible(true); 76 } 77 public static void main(string[] args) { 78 (new MeaningOfLife()).createGUI(); 79 } 80 } Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads SwingWorker class: example The doinbackground() code does not affect the Do something else button (nor any other GUI event) The done() method takes care of signaling the result or a cancellation in the first JLabel writing the JLabel in case of cancellation is done by catching the InterruptedException Federico Pecora Java for Interfaces and Networks Lecture 10 18 / 29

Worker Threads Tasks with interim results SwingWorker provides an easy way to share the result of a worker thread with the event dispatch thread So what if one needs to share intermediate results? SwingWorker provides two methods protected final void publish(t2... chunks) to be used in the worker thread, i.e., in doinbackground() makes intermediate results available to the process() method takes arbitrary number of parameters of type T2 protected void process(list<t2> chunks) invoked automatically in the event dispatch thread receives information asynchronously from the publish() method Federico Pecora Java for Interfaces and Networks Lecture 10 19 / 29

Worker Threads Tasks with interim results The method process() method is invoked asynchronously Therefore there may be several invocations of publish() before process() can occur For performance purposes, multiple invocations of publish() are coalesced into one invocation of process() publish("1"); publish("2", "3"); publish("4", "5", "6");... can result in process("1", "2", "3", "4", "5", "6") Federico Pecora Java for Interfaces and Networks Lecture 10 20 / 29

Worker Threads SwingWorkers with publish() and process() SwingWorker pseudocode 1 class MyWorker extends SwingWorker<Type1, Type2> { 2 //This method executed in worker thread 3 public Type1 doinbackground() { 4 Type2 partialresult; 5 //do something long... 6 publish(partialresult); 7 //continue doing something long... 8 //return result of type Type1 9 } 10 //This method executed in event dispatch thread 11 public void done() { 12 //use result of type Type1 13 } 14 //This method executed in event dispatch thread 15 public void process(list<type2> chunks) { 16 //use chunks (partial result of type Type2) 17 } 18 } Federico Pecora Java for Interfaces and Networks Lecture 10 21 / 29

Worker Threads SwingWorker with interim results: example An application that checks for fairness of java.util.random (inspired by Concurrency in Swing tutorial by Sun) Until canceled, the worker thread extracts n {0,1} and publishes the proportion of 1s Federico Pecora Java for Interfaces and Networks Lecture 10 22 / 29

Worker Threads SwingWorker with interim results: example TestRandomFairness.java 1 public class TestRandomFairness { 2 private PieChart piechart = null; 3 private JButton startb = null; 4 private JButton cancelb = null; 5 private TestRandomWorker worker = null; 6 //... Federico Pecora Java for Interfaces and Networks Lecture 10 22 / 29

Worker Threads SwingWorker with interim results: example TestRandomFairness.java (cont.) 7 private class TestRandomWorker 8 extends SwingWorker<Void, Integer> { 9 public Void doinbackground() { 10 int nrheads = 0; 11 int totaldraws = 0; 12 while (!iscancelled()) { 13 Random rand = new Random(); 14 nrheads += rand.nextint(2); 15 totaldraws++; 16 publish((int)(((float)nrheads/totaldraws)*100)); 17 } 18 return null; 19 } 20 protected void process(list<integer> chunks) { 21 System.out.println("Updating chart..."); 22 piechart.setvalue(chunks.get(chunks.size()-1)); 23 } 24 } //class TestRandomWorker 25 //... Federico Pecora Java for Interfaces and Networks Lecture 10 22 / 29

Worker Threads SwingWorker with interim results: example TestRandomFairness.java (cont.) 26 public void creategui() { 27 JFrame f = new JFrame("Fairness of Random"); 28 startb = new JButton("Start"); 29 cancelb = new JButton("Cancel"); 30 //do lots of GUI creation stuff... see LATER! 31 startb.addactionlistener(new ActionListener(){ 32 public void actionperformed(actionevent arg0) { 33 worker = new TestRandomWorker(); 34 worker.execute(); 35 startb.setenabled(false); 36 cancelb.setenabled(true); 37 } 38 }); 39 //... Federico Pecora Java for Interfaces and Networks Lecture 10 22 / 29

Worker Threads SwingWorker with interim results: example TestRandomFairness.java (cont.) 40 cancelb.addactionlistener(new ActionListener(){ 41 public void actionperformed(actionevent arg0) { 42 worker.cancel(true); 43 worker = null; 44 startb.setenabled(true); 45 cancelb.setenabled(false); 46 } 47 }); 48 //... Federico Pecora Java for Interfaces and Networks Lecture 10 22 / 29

Worker Threads SwingWorker with interim results: example TestRandomFairness.java (cont.) 49 f.setvisible(true); 50 f.setdefaultcloseoperation(jframe.exit_on_close); 51 } //creategui 52 public static void main(string[] args) { 53 TestRandomFairness example = new TestRandomFairness(); 54 example.creategui(); 55 } //main 56 } //class TestRandomFairness Federico Pecora Java for Interfaces and Networks Lecture 10 22 / 29

Worker Threads SwingWorker with interim results: example Notice the pie chart... let s relax now and see how that is done :-) Federico Pecora Java for Interfaces and Networks Lecture 10 22 / 29

Creating Your Own Swing Components Outline 1 Scheduling Application Code on Event Threads 2 Worker Threads 3 Creating Your Own Swing Components Federico Pecora Java for Interfaces and Networks Lecture 10 23 / 29

Creating Your Own Swing Components Your own Swing components As you extend JFrame, you can extend other Swing components to add your own functionality For instance, a simple JPanel can be used as is for the purpose of containing other components But JPanel can also be extended to contain your own non-swing contents A class extending JPanel inherits from JComponent the repaint() method which is automatically re-draws the contents e.g., the pie chart in the previous example, which repaints when a value is changed Federico Pecora Java for Interfaces and Networks Lecture 10 24 / 29

Creating Your Own Swing Components Example: a simple pie chart PieChart.java 1 class PieChart extends JPanel { 2 private int value; 3 private int max; 4 public PieChart(int value, int max) { 5 if (max <= 0) 6 throw new IllegalArgumentException("max = " + max + 7 ", should be > 0"); 8 if (value < 0 value > max) 9 throw new IllegalArgumentException("value = " + value + 10 " should be in 0.." + max); 11 this.value = value; 12 this.max = max; 13 setbackground(color.white); 14 } 15 public PieChart(int value) { this(value, 100); } 16 public PieChart() { this(0, 100); } 17 //... Federico Pecora Java for Interfaces and Networks Lecture 10 25 / 29

Creating Your Own Swing Components Example: a simple pie chart PieChart.java (cont.) 18 public void setvalue(int value) { 19 if (value < 0 value > max) 20 throw new IllegalArgumentException("value = " + value + 21 ", should be in 0.." + max); 22 this.value = value; 23 repaint(); 24 } 25 //... Federico Pecora Java for Interfaces and Networks Lecture 10 25 / 29

Creating Your Own Swing Components Example: a simple pie chart PieChart.java (cont.) 26 public void paintcomponent(graphics g) { 27 super.paintcomponent(g); 28 g.setcolor(color.blue); 29 Insets i = getinsets(); 30 int width = getwidth() - i.left - i.right; 31 int height = getheight() - i.top - i.bottom; 32 int diameter = Math.min(width, height); 33 int x = i.left + (width - diameter) / 2; 34 int y = i.top + (height - diameter) / 2; 35 g.drawoval(x, y, diameter, diameter); 36 double proportion = (double)value / max; 37 int angle = (int)(proportion * 360 + 0.5); 38 g.fillarc(x, y, diameter, diameter, 90, -angle); 39 } 40 } //class PieChart Federico Pecora Java for Interfaces and Networks Lecture 10 25 / 29

Creating Your Own Swing Components Example: a simple pie chart PieChart is essentially a JPanel which maintains a value for determining how much of a circle to fill in The operation of calculating the image is done in the overridden method void paintcomponent(graphics g) a Graphics object provides information for basic rendering (e.g., current color, etc.) g is passed to the method void JComponent.paint(Graphics) which actually does the rendering The overridden method repaint() is called when the PieChart is given a new value JComponent.repaint() calls component s update method as soon as possible Federico Pecora Java for Interfaces and Networks Lecture 10 25 / 29

Creating Your Own Swing Components Example: a simple pie chart TestRandomFairness.java (part.) 26 public void creategui() { 27 JFrame f = new JFrame("Fairness of Random"); 28 f.setsize(520, 590); 29 Container content = f.getcontentpane(); 30 content.setbackground(color.white); 31 content.setlayout(new BorderLayout()); 32 piechart = new PieChart(0,100); 33 piechart.setborder(new EtchedBorder()); 34 content.add(piechart, BorderLayout.CENTER); 35 startb = new JButton("Start"); 36 cancelb = new JButton("Cancel"); 37 cancelb.setenabled(false); 38 content.add(startb, BorderLayout.NORTH); 39 content.add(cancelb, BorderLayout.SOUTH); 40 //define and add the ActionListeners... 41 f.setvisible(true); 42 f.setdefaultcloseoperation(jframe.exit_on_close); 43 } Federico Pecora Java for Interfaces and Networks Lecture 10 25 / 29

Creating Your Own Swing Components Other EventListeners We can continue our pie chart example to illustrate another feature of the listener mechanisms provided by Java JButtons, for instance, can be hooked to ActionListeners ActionListener implementations are triggered when an action is taken on a component ActionListeners are just an example (a sub-interface) of the interface EventListener Other EventListeners exists, e.g., ChangeListener ChangeListener implementations are triggered when the status of a component changes Federico Pecora Java for Interfaces and Networks Lecture 10 26 / 29

Creating Your Own Swing Components Other EventListeners: ChengeEvent For instance, a ChangeListener can detect when a button is pressed programmatically rather than by the user (i.e., no action was taken) We can use ChangeListeners when we need to react to state change in a component These events are instances of class ChangeEvent, which in turn is a subclass of EventObject there are many EventObjects: ChangeEvent, ConnectionEvent, DragGestureEvent,... every EventObject provides a method getsource(), which returns the Object on which the event has occurred Example... Federico Pecora Java for Interfaces and Networks Lecture 10 27 / 29

Creating Your Own Swing Components Other EventListeners: example A GUI with a JSlider that can control the pie chart and a JButton that resets the pie chart to zero Federico Pecora Java for Interfaces and Networks Lecture 10 28 / 29

Creating Your Own Swing Components Other EventListeners: example SliderButtonChart.java 1 class SliderButtonChart extends JFrame { 2 private PieChart piechart = new PieChart(0, 100); 3 public SliderButtonChart(String title) { 4 super(title); 5 Container cp = getcontentpane(); 6 cp.setlayout(new BorderLayout()); 7 piechart.setborder(new EtchedBorder()); 8 cp.add(piechart, BorderLayout.CENTER); 9 JPanel p = new JPanel(); 10 p.setlayout(new FlowLayout()); 11 //... Federico Pecora Java for Interfaces and Networks Lecture 10 28 / 29

Creating Your Own Swing Components Other EventListeners: example SliderButtonChart.java (cont.) 12 final JSlider slider = new JSlider(0, 100, 0); 13 slider.addchangelistener(new ChangeListener() { 14 public void statechanged(changeevent e) { 15 piechart.setvalue(((jslider)e.getsource()).getvalue()); 16 } 17 }); 18 p.add(slider); 19 JButton b = new JButton("Reset"); 20 b.addactionlistener(new ActionListener() { 21 public void actionperformed(actionevent e) { 22 slider.setvalue(0); 23 piechart.setvalue(0); 24 } 25 }); 26 p.add(b); 27 cp.add(p, BorderLayout.SOUTH); 28 } 29 //... Federico Pecora Java for Interfaces and Networks Lecture 10 28 / 29

Creating Your Own Swing Components Other EventListeners: example SliderButtonChart.java (cont.) 30 public static void main(string[] args) { 31 SliderButtonChart g = 32 new SliderButtonChart("PieChart with Slider Demo"); 33 g.setdefaultcloseoperation(jframe.exit_on_close); 34 g.setsize(400, 400); 35 g.setvisible(true); 36 } //main 37 } //class SliderButtonChart Federico Pecora Java for Interfaces and Networks Lecture 10 28 / 29

Creating Your Own Swing Components More on Swing and Threads Thank you! Federico Pecora Java for Interfaces and Networks Lecture 10 29 / 29