Java for Interfaces and Networks (DT3010, HT10)

Size: px
Start display at page:

Download "Java for Interfaces and Networks (DT3010, HT10)"

Transcription

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

2 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

3 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

4 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

5 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

6 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

7 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 // private class ChatButtonWindow extends JFrame { 27 public ChatButtonWindow() { 28 super("extra chat buttons"); 29 Container cp = getcontentpane(); 30 // 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

8 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

9 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

10 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

11 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

12 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

13 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 / 29

14 Scheduling Application Code on Event Threads Chat client using invokelater We add a member Runnable class to manipulate the JTextField ClientWithButtonsNew.java (cont.) 25 // 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 / 29

15 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 / 29

16 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 / 29

17 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 / 29

18 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 / 29

19 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 } 14 } 15 // MyWorker worker = new MyWorker(); 17 worker.execute(); Federico Pecora Java for Interfaces and Networks Lecture / 29

20 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 / 29

21 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 / 29

22 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 / 29

23 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 / 29

24 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( ) == 42) 20 return "The answer is 42"; 21 } 22 } 23 //... Federico Pecora Java for Interfaces and Networks Lecture / 29

25 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 / 29

26 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 //... Federico Pecora Java for Interfaces and Networks Lecture / 29

27 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 / 29

28 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 / 29

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 / 29

30 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 / 29

31 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 / 29

32 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 / 29

33 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 / 29

34 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 / 29

35 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 / 29

36 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 / 29

37 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 / 29

38 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 / 29

39 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 / 29

40 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 / 29

41 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 / 29

42 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 / 29

43 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 / 29

44 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 / 29

45 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 * ); 38 g.fillarc(x, y, diameter, diameter, 90, -angle); 39 } 40 } //class PieChart Federico Pecora Java for Interfaces and Networks Lecture / 29

46 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 / 29

47 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 f.setvisible(true); 42 f.setdefaultcloseoperation(jframe.exit_on_close); 43 } Federico Pecora Java for Interfaces and Networks Lecture / 29

48 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 / 29

49 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 / 29

50 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 / 29

51 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 / 29

52 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 / 29

53 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 / 29

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

Java for Interfaces and Networks (DT3029)

Java for Interfaces and Networks (DT3029) Java for Interfaces and Networks (DT3029) Lecture 9 More on Swing and Threads Federico Pecora federico.pecora@oru.se Center for Applied Autonomous Sensor Systems (AASS) Örebro University, Sweden www.clipartlord.com

More information

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 2.2] GUI FRAMEWORKS & CONCURRENCY 1 GUI FRAMEWORKS & CONCURRENCY Once upon a time GUI applications

More information

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

EPITA Première Année Cycle Ingénieur. Atelier Java - J5 EPITA Première Année Cycle Ingénieur marwan.burelle@lse.epita.fr http://www.lse.epita.fr Overview 1 2 Different toolkits AWT: the good-old one, lakes some features and has a plateform specific look n

More information

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

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class. Q1. If you add a component to the CENTER of a border layout, which directions will the component stretch? A1. The component will stretch both horizontally and vertically. It will occupy the whole space

More information

Java for Interfaces and Networks (DT3010, HT10)

Java for Interfaces and Networks (DT3010, HT10) Java for Interfaces and Networks (DT3010, HT10) Inner Classes Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks

More information

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

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008 Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008 Announcements A3 is up, due Friday, Oct 10 Prelim 1 scheduled for Oct 16 if you have a conflict, let us know now 2 Interactive

More information

MIT AITI Swing Event Model Lecture 17

MIT AITI Swing Event Model Lecture 17 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 user. But how do GUIs interact with users? How do applications

More information

CS108, Stanford Handout #22. Thread 3 GUI

CS108, Stanford Handout #22. Thread 3 GUI CS108, Stanford Handout #22 Winter, 2006-07 Nick Parlante Thread 3 GUI GUIs and Threading Problem: Swing vs. Threads How to integrate the Swing/GUI/drawing system with threads? Problem: The GUI system

More information

Points Missed on Page page 1 of 8

Points Missed on Page page 1 of 8 Midterm II - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total. Name: ID: Problem #1 (8 points) Rewrite the following code segment using a for loop instead of a while loop (that is

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphic User Interfaces. - GUI concepts - Swing - AWT Graphic User Interfaces - GUI concepts - Swing - AWT 1 What is GUI Graphic User Interfaces are used in programs to communicate more efficiently with computer users MacOS MS Windows X Windows etc 2 Considerations

More information

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

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions. Parts of a Contract Syntax - Method signature Method name Parameter list Return type Semantics - Comments Preconditions: requirements placed on the caller Postconditions: what the method modifies and/or

More information

AP CS Unit 11: Graphics and Events

AP CS Unit 11: Graphics and Events AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two

More information

Graphical User Interfaces. Comp 152

Graphical User Interfaces. Comp 152 Graphical User Interfaces Comp 152 Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from

More information

Lecture 5: Java Graphics

Lecture 5: Java Graphics Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,

More information

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

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1 Datenbank-Praktikum Universität zu Lübeck Sommersemester 2006 Lecture: Swing Ho Ngoc Duc 1 Learning objectives GUI applications Font, Color, Image Running Applets as applications Swing Components q q Text

More information

Part I: Learn Common Graphics Components

Part I: Learn Common Graphics Components OOP GUI Components and Event Handling Page 1 Objectives 1. Practice creating and using graphical components. 2. Practice adding Event Listeners to handle the events and do something. 3. Learn how to connect

More information

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

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

More information

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

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages. 1 CS257 Computer Science I Kevin Sahr, PhD Lecture 14: Graphical User Interfaces Command-Line Applications 2 The programs we've explored thus far have been text-based applications A Java application is

More information

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

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction CSC 160 LAB 8-1 DIGITAL PICTURE FRAME PROFESSOR GODFREY MUGANDA DEPARTMENT OF COMPUTER SCIENCE 1. Introduction Download and unzip the images folder from the course website. The folder contains 28 images

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Agenda. Container and Component

Agenda. Container and Component Agenda Types of GUI classes/objects Step-by-step guide to create a graphic user interface Step-by-step guide to event-handling PS5 Problem 1 PS5 Problem 2 Container and Component There are two types of

More information

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Graphic Interface Programming II Events and Threads. Uppsala universitet

Graphic Interface Programming II Events and Threads. Uppsala universitet Graphic Interface Programming II Events and Threads IT Uppsala universitet Animation Animation adds to user experience Done right, it enhances the User Interface Done wrong, it distracts and irritates

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

Java for Interfaces and Networks

Java for Interfaces and Networks Java for Interfaces and Networks Threads and Networking Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks Lecture

More information

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

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid Systems Programming Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid Leganés, 21st of March, 2014. Duration: 75 min. Full

More information

Introduction. Introduction

Introduction. Introduction Introduction Many Java application use a graphical user interface or GUI (pronounced gooey ). A GUI is a graphical window or windows that provide interaction with the user. GUI s accept input from: the

More information

Java for Interfaces and Networks (DT3010, HT10)

Java for Interfaces and Networks (DT3010, HT10) Java for Interfaces and Networks (DT3010, HT10) Mouse Events, Timers, Serialization Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces

More information

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

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons CompSci 125 Lecture 17 GUI: Graphics, Check Boxes, Radio Buttons Announcements GUI Review Review: Inheritance Subclass is a Parent class Includes parent s features May Extend May Modify extends! Parent

More information

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

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical

More information

G51PRG: Introduction to Programming Second semester Applets and graphics

G51PRG: Introduction to Programming Second semester Applets and graphics G51PRG: Introduction to Programming Second semester Applets and graphics Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk Previous two lectures AWT and Swing Creating components and putting

More information

CS 251 Intermediate Programming GUIs: Event Listeners

CS 251 Intermediate Programming GUIs: Event Listeners CS 251 Intermediate Programming GUIs: Event Listeners Brooke Chenoweth University of New Mexico Fall 2017 What is an Event Listener? A small class that implements a particular listener interface. Listener

More information

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. SOLUTION HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2006 FINAL EXAMINATION 7pm to 10pm, 19 DECEMBER 2006, Jeffrey Hall 1 st Floor Instructor:

More information

CS193j, Stanford Handout #21. Threading 3

CS193j, Stanford Handout #21. Threading 3 CS193j, Stanford Handout #21 Summer, 2003 Manu Kumar Threading 3 Thread Challenge #2 -- wait/ Co-ordination Synchronization is the first order problem with concurrency. The second problem is coordination

More information

User interfaces and Swing

User interfaces and Swing User interfaces and Swing Overview, applets, drawing, action listening, layout managers. APIs: java.awt.*, javax.swing.*, classes names start with a J. Java Lectures 1 2 Applets public class Simple extends

More information

Lecture 3: Java Graphics & Events

Lecture 3: Java Graphics & Events Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new

More information

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

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"

More information

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!

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! Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques

More information

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

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components CS112-Section2 Hakan Guldas Burcin Ozcan Meltem Kaya Muge Celiktas Notes of 6-8 May Graphics Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how

More information

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

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

More information

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

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)

More information

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

Question 1. Show the steps that are involved in sorting the string SORTME using the quicksort algorithm given below. Name: 1.124 Quiz 2 Thursday November 9, 2000 Time: 1 hour 20 minutes Answer all questions. All questions carry equal marks. Question 1. Show the steps that are involved in sorting the string SORTME using

More information

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

JRadioButton account_type_radio_button2 = new JRadioButton(Current); ButtonGroup account_type_button_group = new ButtonGroup(); Q)Write a program to design an interface containing fields User ID, Password and Account type, and buttons login, cancel, edit by mixing border layout and flow layout. Add events handling to the button

More information

Swing from A to Z Some Simple Components. Preface

Swing from A to Z Some Simple Components. Preface By Richard G. Baldwin baldwin.richard@iname.com Java Programming, Lecture Notes # 1005 July 31, 2000 Swing from A to Z Some Simple Components Preface Introduction Sample Program Interesting Code Fragments

More information

Java Programming Lecture 6

Java Programming Lecture 6 Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32 Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components

More information

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

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University Java Swing Recitation 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University Announcements Project 8 is out Milestone due on Dec 3rd, 10:00 pm Final due on Dec 10th, 10:00 pm No classes,

More information

Window Interfaces Using Swing. Chapter 12

Window Interfaces Using Swing. Chapter 12 Window Interfaces Using Swing 1 Reminders Project 7 due Nov 17 @ 10:30 pm Project 6 grades released: regrades due by next Friday (11-18-2005) at midnight 2 GUIs - Graphical User Interfaces Windowing systems

More information

Graphical User Interfaces (GUIs)

Graphical User Interfaces (GUIs) CMSC 132: Object-Oriented Programming II Graphical User Interfaces (GUIs) Department of Computer Science University of Maryland, College Park Model-View-Controller (MVC) Model for GUI programming (Xerox

More information

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7 PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,

More information

Java for Interfaces and Networks (DT3029)

Java for Interfaces and Networks (DT3029) Java for Interfaces and Networks (DT3029) Lecture 3 Threads and Networking Federico Pecora federico.pecora@oru.se Center for Applied Autonomous Sensor Systems (AASS) Örebro University, Sweden Capiscum

More information

Graphical interfaces & event-driven programming

Graphical interfaces & event-driven programming Graphical interfaces & event-driven programming Lecture 12 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017 Pop quiz!

More information

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

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Graphics programming COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Overview Aims To provide an overview of Swing and the AWT To show how to build

More information

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

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment. Handouts CS193J: Programming in Java Summer Quarter 2003 Lecture 10 Thread Interruption, Cooperation (wait/notify), Swing Thread, Threading conclusions 1 Handout for today! #21: Threading 3 #22: HW3a:

More information

Programming graphics

Programming graphics Programming graphics Need a window javax.swing.jframe Several essential steps to use (necessary plumbing ): Set the size width and height in pixels Set a title (optional), and a close operation Make it

More information

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

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by

More information

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

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule

More information

INTRODUCTION TO (GUIS)

INTRODUCTION TO (GUIS) INTRODUCTION TO GRAPHICAL USER INTERFACES (GUIS) Lecture 10 CS2110 Fall 2009 Announcements 2 A3 will be posted shortly, please start early Prelim 1: Thursday October 14, Uris Hall G01 We do NOT have any

More information

Introduction to concurrency and GUIs

Introduction to concurrency and GUIs Principles of Software Construction: Objects, Design, and Concurrency Part 2: Designing (Sub)systems Introduction to concurrency and GUIs Charlie Garrod Bogdan Vasilescu School of Computer Science 1 Administrivia

More information

Java: Graphical User Interfaces (GUI)

Java: Graphical User Interfaces (GUI) Chair of Software Engineering Carlo A. Furia, Marco Piccioni, and Bertrand Meyer Java: Graphical User Interfaces (GUI) With material from Christoph Angerer The essence of the Java Graphics API Application

More information

We are on the GUI fast track path

We are on the GUI fast track path We are on the GUI fast track path Chapter 13: Exception Handling Skip for now Chapter 14: Abstract Classes and Interfaces Sections 1 9: ActionListener interface Chapter 15: Graphics Skip for now Chapter

More information

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

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13 CONTENTS Chapter 1 Getting Started with Java SE 6 1 Introduction of Java SE 6... 3 Desktop Improvements... 3 Core Improvements... 4 Getting and Installing Java... 5 A Simple Java Program... 10 Compiling

More information

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

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

Jonathan Aldrich Charlie Garrod

Jonathan Aldrich Charlie Garrod Principles of Software Construction: Objects, Design, and Concurrency (Part 3: Design Case Studies) Introduction to GUIs Jonathan Aldrich Charlie Garrod School of Computer Science 1 Administrivia Homework

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

Class 16: The Swing Event Model

Class 16: The Swing Event Model Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #19: November 4, 2015 1/14 Third Exam The third, Checkpoint Exam, will be on: Wednesday, November 11, 2:30 to 3:45 pm You will have 3 questions, out of 9,

More information

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 2 2 Develop the layout of those elements 3 3 Add listeners to the elements 9 4 Implement custom drawing 12 1 The StringArt Program To illustrate

More information

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 3 2 Develop the layout of those elements 4 3 Add listeners to the elements 12 4 Implement custom drawing 15 1 The StringArt Program To illustrate

More information

Introduction to the JAVA UI classes Advanced HCI IAT351

Introduction to the JAVA UI classes Advanced HCI IAT351 Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing

More information

Implementing Graphical User Interfaces

Implementing Graphical User Interfaces Chapter 6 Implementing Graphical User Interfaces 6.1 Introduction To see aggregation and inheritance in action, we implement a graphical user interface (GUI for short). This chapter is not about GUIs,

More information

Assignment 2. Application Development

Assignment 2. Application Development Application Development Assignment 2 Content Application Development Day 2 Lecture The lecture covers the key language elements of the Java programming language. You are introduced to numerical data and

More information

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

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place. Chapter 8 Java continued CS3283 - Hugh Anderson s notes. Page number: 263 ALERT MCQ test next week This time This place Closed book CS3283 - Hugh Anderson s notes. Page number: 264 ALERT Assignment #2

More information

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

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 Chapter 8 Java continued MCQ test next week This time This place Closed book ALERT CS3283 - Hugh Anderson s notes. Page number: 263 CS3283 - Hugh Anderson s notes. Page number: 264 ALERT Last week Assignment

More information

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC124, WINTER TERM, 2009 FINAL EXAMINATION 7pm to 10pm, 18 APRIL 2009, Dunning Hall Instructor: Alan McLeod If the

More information

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

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 Welcome to! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) Overview JAVA and GUIs: SWING Container, Components, Layouts Using SWING Streams and Files Text

More information

Graphical User Interfaces in Java - SWING

Graphical User Interfaces in Java - SWING Graphical User Interfaces in Java - SWING Graphical User Interfaces (GUI) Each graphical component that the user can see on the screen corresponds to an object of a class Component: Window Button Menu...

More information

Class 34: Introduction to Threads

Class 34: Introduction to Threads Introduction to Computation and Problem Solving Class 34: Introduction to Threads Prof. Steven R. Lerman and Dr. V. Judson Harward What is a Thread? Imagine a Java program that is reading large files over

More information

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

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like: OOP Assignment V If we don t use multithreading, or a timer, and update the contents of the applet continuously by calling the repaint() method, the processor has to update frames at a blinding rate. Too

More information

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

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1 Block I Unit 2 Basic Constructs in Java M301 Block I, unit 2 1 Developing a Simple Java Program Objectives: Create a simple object using a constructor. Create and display a window frame. Paint a message

More information

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming Objectives: Last revised 1/15/10 1. To introduce the notion of a component and some basic Swing components (JLabel, JTextField, JTextArea,

More information

CS193k, Stanford Handout #10. Threads 4 / RMI

CS193k, Stanford Handout #10. Threads 4 / RMI CS193k, Stanford Handout #10 Spring, 2000-01 Nick Parlante Threads 4 / RMI Semaphore2 Alternate implementation -- possibly more readable. Does the wait/decrement in a different order. Uses the classic

More information

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

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Swing UI by Vlad Costel Ungureanu for Learn Stuff User Interface Command Line Graphical User Interface (GUI) Tactile User Interface (TUI) Multimedia (voice) Intelligent (gesture recognition) 2 Making the

More information

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

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts SE1021 Exam 2 Name: You may use a note-sheet for this exam. But all answers should be your own, not from slides or text. Review all questions before you get started. The exam is printed single-sided. Write

More information

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

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

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

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2012 CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2012 Name: This exam consists of 6 problems on the following 8 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

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

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 List of Slides 1 Title 2 Chapter 13: Graphical user interfaces 3 Chapter aims 4 Section 2: Example:Hello world with a GUI 5 Aim 6 Hello world with a GUI 7 Hello world with a GUI 8 Package: java.awt and

More information

Packages: Putting Classes Together

Packages: Putting Classes Together Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic

More information

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

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { } CBOP3203 What Is an Event? Events Objects that describe what happened Event Sources The generator of an event Event Handlers A method that receives an event object, deciphers it, and processes the user

More information

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

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling Handout 12 CS603 Object-Oriented Programming Fall 15 Page 1 of 12 Handout 14 Graphical User Interface (GUI) with Swing, Event Handling The Swing library (javax.swing.*) Contains classes that implement

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 29 Nov. 19, 2010 Swing I Event- driven programming Passive: ApplicaHon waits for an event to happen in the environment When an event occurs, the applicahon

More information

AnimatedImage.java. Page 1

AnimatedImage.java. Page 1 1 import javax.swing.japplet; 2 import javax.swing.jbutton; 3 import javax.swing.jpanel; 4 import javax.swing.jcombobox; 5 import javax.swing.jlabel; 6 import javax.swing.imageicon; 7 import javax.swing.swingutilities;

More information

PIC 20A GUI with swing

PIC 20A GUI with swing PIC 20A GUI with swing Ernest Ryu UCLA Mathematics Last edited: November 22, 2017 Hello swing Let s create a JFrame. import javax. swing.*; public class Test { public static void main ( String [] args

More information

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. QUEEN'S UNIVERSITY SCHOOL OF COMPUTING HAND IN Answers Are Recorded on Question Paper CMPE212, FALL TERM, 2012 FINAL EXAMINATION 18 December 2012, 2pm Instructor: Alan McLeod If the instructor is unavailable

More information

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

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping. HW#1: Pencil Me In Status!? CS193J: Programming in Java Summer Quarter 2003 Lecture 6 Inner Classes, Listeners, Repaint Manu Kumar sneaker@stanford.edu How was Homework #1? Comments please? SITN students

More information

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

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015 CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 6 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. QUEEN'S UNIVERSITY SCHOOL OF COMPUTING HAND IN Answers Are Recorded on Question Paper CISC124, WINTER TERM, 2011 FINAL EXAMINATION 7pm to 10pm, 26 APRIL 2011, Ross Gym Instructor: Alan McLeod If the instructor

More information

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

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2006 FINAL EXAMINATION 7pm to 10pm, 19 DECEMBER 2006, Jeffrey Hall 1 st Floor Instructor: Alan

More information