Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.

Slides:



Advertisements
Similar presentations
Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)
Advertisements

1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
OLD BUSINESS : Lets talk about the next exam Project proposals – Functional Definitions Go over homework – NEW BUSINESS: Chapter 4 today GUIs Assignment.
Java Graphical User Interface (GUI) using Visual Editor in eclipse CSI 1390 – Java Programming Instructor: Saeid Nourian University.
Made with love, by Zachary Langley Applets The Graphics Presentation.
1 cs205: engineering software university of virginia fall 2006 Wimpy Interfaces.
Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
Web Design & Development Lecture 19. Java Graphics 2.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
Java Applets:. How Applets differ from application?: They do not use main method but init(), start() and paint() methods of the applet class They can.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Graphical User Interfaces (Part IV)
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
CS18000: Problem Solving and Object-Oriented Programming.
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
The Model-View Approach in Java. OK, you’ve got “Hello World” running... What now?
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
TCU CoSc Programming with Java Handling Events.
Things to mention public static void main(String [] args) –The starting point for a free-standing Java application (i.e. one not run from the DrJava interactions.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
CS 178: Programming with Multimedia Objects Aditya P. Mathur Professor of Computer Sciences Purdue University, West Lafayette Sept 9, 2004 Last update:
Event Handling Events and Listeners Timers and Animation.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Chapter 7 GUI design. So far this semester Have programmed in a stop and wait mode Program displays dialog box and waits for user to respond This was.
Chapter Day 9. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 8 Questions from last Class?? Problem set 2 posted  10 programs from.
Io package as Java’s basic I/O system continue’d.
Applets, AWTS CompSci 230 Software Construction.
EE2E1. JAVA Programming Lecture 8 Multi-threading.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
CS12420 – Swing and threads Lynda Thomas
Applets and Frames CS 21a: Introduction to Computing I First Semester,
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Not all java code is an application! Applets, Webstart and Servlets Warning: this is just to show you where to look and some things to look for – by no.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Concurrent Programming and Threads Threads Blocking a User Interface.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
UID – Event Handling and Listeners Boriana Koleva
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
(1) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
Review_6 AWT, Swing, ActionListener, and Graphics.
Applets Java code is compiled into byte code instead of machine language –Languages like C, C++, Pascal and others are compiled into machine language so.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Event Handling CS 21a: Introduction to Computing I First Semester,
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Chapter 11: Threaded Programs Situations where the program is following multiple execution paths (how to stop one?) Thread: a line of execution Thread.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Chapter 13: Multithreading
Lecture 09 Applets.
Lecture 28 Concurrent, Responsive GUIs
Event Handling CS 21a: Introduction to Computing I
Threads II IS
Using threads for long running tasks.
Presentation transcript:

Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth

Talk overview Handling computationally complex work in a JApplet or other Swing based application. SwingWorker – Java 5 Approach SwingWorker – Java 6 Approach

Doing computational complex work in an Applet Interface can “freeze” Need thus to do computation on another thread Can use SwingWorker Was extra download with Java 5 Now part of Java 6, but with redesigned interface

SwingWorker in Java 5 import java.awt.*; import javax.swing.*; import java.awt.event.*; // This example by Dave Price inspired by code from Lynda Thomas // The example shows how to use SwingUtilities.invokeAndWait // to build a user interface. // It also shows how to do computationally intensive // work in a separate thread use the SwingWorker class. // NOTE: This uses the non-jvm versions of SwingWorker which // developers had to download and compile with their classes. // Java 6 now includes an implementation of SwingWorker // but with slightly different methods and usage etc. // Note: This also includes a button that tries to directly // cause computationally intensive code to run and thus, // if used, causes the whole Swing interface to lock up, indeed // it can even cause the browser to freeze. // There is also another interesting "feature". If a user // clicks the "run" button multiple times you end up // with multiple SwingWorker threads, each trying to update // the displayed counter text. Try doing this and watch effect. // Clicking the stop button after multiple run clicks fixes // it though as all threads spot that they are supposed to stop.

public class JTestSwing extends JApplet implements ActionListener { JPanel buttonPanel; NewPanel myMessageSpace; JButton runButton, runWrongButton, stopButton; public void init() { // In this init method we ask the event dispatch thread // to build our user interface rather than doing it ourself try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { buildTestGui(); } }); } catch (Exception e) { System.err.println("Attempt to use invokeAndWait threw exception " + e); }

public void buildTestGui() { // This method builds our user interface buttonPanel=new JPanel(); runButton=new JButton("run"); runWrongButton=new JButton("runWrong"); stopButton=new JButton("stop"); buttonPanel.add(runButton); buttonPanel.add(runWrongButton); buttonPanel.add(stopButton); runButton.addActionListener(this); runWrongButton.addActionListener(this); stopButton.addActionListener(this); getContentPane().add("North",buttonPanel); myMessageSpace=new NewPanel("Click to make live!"); myMessageSpace.setMinimumSize(new Dimension(50,200)); myMessageSpace.setBorder(BorderFactory.createLineBorder(Color.black,6)); getContentPane().add("Center",myMessageSpace); setVisible(true); }

public void actionPerformed(ActionEvent e){ // This checks which button was pressed and calls // the appropriate method if (e.getSource()==runButton) myMessageSpace.startCalc(); if (e.getSource()==runWrongButton) myMessageSpace.sillyCalc(); if (e.getSource()==stopButton){ myMessageSpace.stopit(); } //class for the message area class NewPanel extends JPanel { private String s; private boolean keepGoing; public NewPanel(String initstring) { setBackground(Color.white); s=initstring; }

public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(s,70,20); } public void startCalc(){ // This method has work to do and so // properly creates a SwingWorker, that is, // another thread to do that work SwingWorker worker = new SwingWorker() { public Object construct() { return doCalc(); } }; // now tell that thread to do its work worker.start(); } public void sillyCalc(){ // This foolish method tries to directly do the work. // This is running in the event dispatch thread which thus gets // stuck in this code and thus the Swing interface freezes // Note: this can even make the whole browser become unusable so // that you have to kill it! doCalc(); }

Object doCalc() { // Now the work itself. This runs // for ever until something manages to // set keepGoing to be false int i=0; keepGoing=true; try{ while (keepGoing) { s="counter "+i+" now"; repaint(); i++; Thread.sleep(200); } catch (InterruptedException e) { return null; } return null; } public void stopit(){ // Someone has now pressed stop button so we can // set keepGoing false which other threads will spot // and thus hopefully stop what they are doing keepGoing=false; s="stopped"; repaint(); }

SwingWorker in Java 6 import java.awt.*; import javax.swing.*; import java.awt.event.*; // This example by Dave Price inspired by code from Lynda Thomas // The example shows how to use SwingUtilities.invokeAndWait // to build a user interface. // It also shows how to do computationally intensive // work in a separate thread use the SwingWorker class. // Note: Java 6 now includes an implementation of SwingWorker // but with slightly different methods and usage etc. // to the previous version of SwingWorker which // developers had to download and compile with their classes. // Note: This also includes a button that tries to directly // cause computationally intensive code to run and thus, // if used, causes the whole Swing interface to lock up, indeed // it can even cause the browser to freeze. // There is also another interesting "feature". If a user // clicks the "run" button multiple times you end up // with multiple SwingWorker threads, each trying to update // the displayed counter text. Try doing this and watch effect. // Clicking the stop button after multiple run clicks fixes // it though as all threads spot that they are supposed to stop.

public class JTestSwing extends JApplet implements ActionListener { JPanel buttonPanel; NewPanel myMessageSpace; JButton runButton, runWrongButton, stopButton; public void init() { // In this init method we ask the event dispatch thread // to build our user interface rather than doing it ourself try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { buildTestGui(); } }); } catch (Exception e) { System.err.println("Attempt to use invokeAndWait threw exception " + e); }

public void buildTestGui() { // This method builds our user interface buttonPanel=new JPanel(); runButton=new JButton("run"); runWrongButton=new JButton("runWrong"); stopButton=new JButton("stop"); buttonPanel.add(runButton); buttonPanel.add(runWrongButton); buttonPanel.add(stopButton); runButton.addActionListener(this); runWrongButton.addActionListener(this); stopButton.addActionListener(this); getContentPane().add("North",buttonPanel); myMessageSpace=new NewPanel("Click to make live!"); myMessageSpace.setMinimumSize(new Dimension(50,200)); myMessageSpace.setBorder(BorderFactory.createLineBorder(Color.black,6)); getContentPane().add("Center",myMessageSpace); setVisible(true); }

public void actionPerformed(ActionEvent e){ // This checks which button was pressed and calls // the appropriate method if (e.getSource()==runButton) myMessageSpace.startCalc(); if (e.getSource()==runWrongButton) myMessageSpace.sillyCalc(); if (e.getSource()==stopButton){ myMessageSpace.stopit(); } //class for the message area class NewPanel extends JPanel { private String s; private boolean keepGoing; public NewPanel(String initstring) { setBackground(Color.white); s=initstring; }

public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(s,70,20); } public void startCalc(){ // This method has work to do and so // properly creates a SwingWorker, that is, // another thread to do that work SwingWorker worker = new SwingWorker () { public Void doInBackground() { return doCalc(); } }; // now tell that thread to do its work worker.execute(); } public void sillyCalc(){ // This foolish method tries to directly do the work. // This is running in the event dispatch thread which thus gets // stuck in this code and thus the Swing interface freezes // Note: this can even make the whole browser become unusable so // that you have to kill it! doCalc(); }

Void doCalc() { // Now the work itself. This runs // for ever until something manages to // set keepGoing to be false int i=0; keepGoing=true; try{ while (keepGoing) { s="counter "+i+" now"; repaint(); i++; Thread.sleep(200); } catch (InterruptedException e) { return null; } return null; } public void stopit(){ // Someone has now pressed stop button so we can // set keepGoing false which other threads will spot // and thus hopefully stop what they are doing keepGoing=false; s="stopped"; repaint(); }

The “Real” differences The comments differ as follows: 13,15c13 < // NOTE: This uses the non-jvm versions of SwingWorker which < // developers had to download and compile with their classes. < // Java 6 now includes an implementation of SwingWorker --- > // Note: Java 6 now includes an implementation of SwingWorker 16a15,16 > // to the previous version of SwingWorker which > // developers had to download and compile with their classes.

The “Real” differences 122,123c122,123 < SwingWorker worker = new SwingWorker() { < public Object construct() { --- > SwingWorker worker = new SwingWorker () { > public Void doInBackground() { 130c130 < worker.start(); --- > worker.execute(); 144c144 < Object doCalc() { --- > Void doCalc() {

Conclusions If you build the GUI on the thread that is executing in the init() method things can go wrong If you directly execute computationally intensive code in the Swing GUI thread then your whole JApplet (or Java Application) can lock up, possibly meaning you have to kill the whole browser or JVM.