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

Similar documents
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

Graphic User Interfaces. - GUI concepts - Swing - AWT

Introduction to the JAVA UI classes Advanced HCI IAT351

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

Window Interfaces Using Swing Objects

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

Systems Programming Graphical User Interfaces

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

Graphical User Interfaces in Java - SWING

Graphical User Interfaces (GUIs)

Window Interfaces Using Swing Objects

CS 251 Intermediate Programming GUIs: Components and Layout

More Swing. CS180 Recitation 12/(04,05)/08

Advanced Java Programming. Swing. Introduction to Swing. Swing libraries. Eran Werner, Tel-Aviv University Summer, 2005

Java: Graphical User Interfaces (GUI)

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

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

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

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

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

(Incomplete) History of GUIs

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Chapter 6: Graphical User Interfaces

Packages: Putting Classes Together

Part I: Learn Common Graphics Components

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

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

Chapter 14. More Swing

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

Graphical User Interfaces. Swing. Jose Jesus García Rueda

Part 3: Graphical User Interface (GUI) & Java Applets

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

encompass a group of features for building Graphical User Interfaces (GUI).

Graphical User Interfaces. Comp 152

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

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

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

CS11 Java. Fall Lecture 4

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Graphical User Interface (GUI)

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

Jonathan Aldrich Charlie Garrod

Sri Vidya College of Engineering & Technology

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

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

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Dr. Hikmat A. M. AbdelJaber

User interfaces and Swing

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

Java. GUI building with the AWT

Programming Language Concepts: Lecture 8

Java IDE Programming-I

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

Graphical interfaces & event-driven programming

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

More Swing. Chapter 14. Chapter 14 1

Building Graphical User Interfaces. Overview

Event Driven Programming

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

Building Graphical User Interfaces. GUI Principles

PIC 20A GUI with swing

CS 251 Intermediate Programming GUIs: Event Listeners

AP CS Unit 11: Graphics and Events

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

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

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT

Chapter 12 Advanced GUIs and Graphics

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Agenda. Container and Component

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

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

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

BASICS OF GRAPHICAL APPS

Final Exam CS 251, Intermediate Programming December 13, 2017

Come & Join Us at VUSTUDENTS.net

Swing from A to Z Some Simple Components. Preface

Programming Languages and Techniques (CIS120e)

Lecture 9. Lecture

JLayeredPane. Depth Constants in JLayeredPane

Programming graphics

Lecture 5: Java Graphics

CSE 8B Intro to CS: Java

Graphical User Interface (GUI)

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

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

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Introduction to concurrency and GUIs

GUI Event Handlers (Part I)

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Today. cisc3120-fall2012-parsons-lectiii.3 2

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

Lecture 18 Java Graphics and GUIs

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

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

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

Java Programming Lecture 6

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

Transcription:

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 is for groups of 3 Like extended version of tkpaint, but has menus persistence compound objects CS3283 - Hugh Anderson s notes. Page number: 265 Last week Tool sets for Java/Swing The relationship between JFC, Java and Swing. Simple first programs CS3283 - Hugh Anderson s notes. Page number: 266

This week Heirarchy Layout managers Simple first programs CS3283 - Hugh Anderson s notes. Page number: 267 Containment heirarchy Top level provides panes for descendants to paint themselves Control-Shift-F1 to view t2[frame0,954,518,126x43,layout=java.awt... javax.swing.jrootpane[,4,24,118x15,la... javax.swing.jpanel[null.glasspane,... javax.swing.jlayeredpane[null.laye... javax.swing.jpanel[null.content... javax.swing.jlabel[,0,0,118x... CS3283 - Hugh Anderson s notes. Page number: 268

Containment heirarchy CS3283 - Hugh Anderson s notes. Page number: 269 Containment heirarchy The glass pane: Intercepts input events for the root pane. The layered pane: Serves to position its contents, which consist of the content pane and the optional menu bar. The content pane: The container of the root pane s visible components, excluding the menu bar. The menu bar: The home for the root pane s container s menus. CS3283 - Hugh Anderson s notes. Page number: 270

Containment heirarchy Level Top-level Mid-level Component-level Container JFrame JApplet JDialog JPanel JScrollBar JTabbedPane JButton JLabel... CS3283 - Hugh Anderson s notes. Page number: 271 Containment heirarchy Every GUI component must be part of a containment hierarchy. Each top-level container has a content pane, and an optional menu bar To view the containment hierarchy for any frame or dialog, click its border to select it, and then press Control-Shift-F1. A list of the containment hierarchy will be written to the standard output stream. CS3283 - Hugh Anderson s notes. Page number: 272

Containment heirarchy Java/Swing components are added to either the content pane or the menu bar. Every component must be placed somewhere in this containment heirarchy, or it will not be visible. CS3283 - Hugh Anderson s notes. Page number: 273 Layout management Every container has a default layout manager It may be over-ridden A range of layout managers supplied These are AWT components, not Swing CS3283 - Hugh Anderson s notes. Page number: 274

BorderLayout BorderLayout is the default layout manager for every content pane, and assists in placing components in the north, south, east, west, and center of the content pane. contentpane.add(new JButton("B1"), BorderLayout.NORTH); CS3283 - Hugh Anderson s notes. Page number: 275 BoxLayout BoxLayout puts components in a single row or column. Here is code to create a centered column of components: pane.setlayout(new BoxLayout(pane, BoxLayout.Y AXIS)); pane.add(label); pane.add(box.createrigidarea(new Dimension(0,5))); pane.add(...); CS3283 - Hugh Anderson s notes. Page number: 276

CardLayout CardLayout is for when a pane has different components at different times. You may think of it as a stack of same-sized cards. cards = new JPanel(); cards.setlayout(new CardLayout()); cards.add(p1, BUTTONPANEL); cards.add(p2, TEXTPANEL); CS3283 - Hugh Anderson s notes. Page number: 277 CardLayout You can choose the top card to show: CardLayout cl = (CardLayout)(cards.getLayout()); cl.show(cards, (String)evt.getItem()); CS3283 - Hugh Anderson s notes. Page number: 278

Creating menus The menu classes are descendants of JComponent, and may be used in any higher-level container class (JApplet and so on). CS3283 - Hugh Anderson s notes. Page number: 279 Creating menus CODE LISTING menutest.java public class menutest extends javax.swing.jframe { public menutest() { initcomponents(); private void initcomponents() { jmenubar1 = new javax.swing.jmenubar(); jmenu1 = new javax.swing.jmenu(); jmenuitem1 = new javax.swing.jmenuitem(); jmenuitem2 = new javax.swing.jmenuitem(); jmenuitem3 = new javax.swing.jmenuitem(); jmenu2 = new javax.swing.jmenu(); jmenuitem4 = new javax.swing.jmenuitem(); jmenu1.settext("file"); jmenuitem1.settext("open"); jmenu1.add(jmenuitem1); jmenuitem2.settext("close"); jmenu1.add(jmenuitem2); jmenuitem3.settext("quit"); jmenuitem3.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent evt) { jmenuitem3actionperformed(evt); ); jmenu1.add(jmenuitem3); jmenubar1.add(jmenu1); jmenu2.settext("edit"); jmenuitem4.settext("cut"); jmenu2.add(jmenuitem4); jmenubar1.add(jmenu2); addwindowlistener(new java.awt.event.windowadapter() { public void windowclosing(java.awt.event.windowevent evt) { exitform(evt); ); setjmenubar(jmenubar1); pack(); private void jmenuitem3actionperformed(java.awt.event.actionevent evt) { System.exit(0); private void exitform(java.awt.event.windowevent evt) { System.exit(0); public static void main(string args[]) { new menutest().show(); private javax.swing.jmenubar jmenubar1; private javax.swing.jmenu jmenu1; private javax.swing.jmenuitem jmenuitem1; private javax.swing.jmenuitem jmenuitem2; private javax.swing.jmenuitem jmenuitem3; private javax.swing.jmenu jmenu2; private javax.swing.jmenuitem jmenuitem4; CS3283 - Hugh Anderson s notes. Page number: 280

Menus The end result is: CS3283 - Hugh Anderson s notes. Page number: 281 Threads in Swing Java supports multi-threading We may have critical sections To create threads use SwingWorker or Timer. CS3283 - Hugh Anderson s notes. Page number: 282

Threads Most Swing components are not thread safe - this means that if two threads call methods on the same Swing component, the results are not guaranteed. The single-thread rule: Swing components accessed by only one thread at a time. CS3283 - Hugh Anderson s notes. Page number: 283 Threads A particular thread, the event-dispatching thread, is the one that normally accesses Swing components. To get access to this thread from another thread we can use invokelater() or invokeandwait(). CS3283 - Hugh Anderson s notes. Page number: 284

Threads Many applications do not require threading, but if you do have threads, then you may have problems debugging your programs. However, you might consider using threads if: Your application has to do some long task, or wait for an external event, without freezing the display. Your application has to do someting at fixed time intervals. CS3283 - Hugh Anderson s notes. Page number: 285 Implementing threads The following two classes are used to implement threads: 1. SwingWorker : To create a thread 2. Timer: Creates a timed thread If you find that your distribution does not include SwingWorker.class, download and compile it. CS3283 - Hugh Anderson s notes. Page number: 286

SwingWorker To use SwingWorker, create a subclass of it, and in the subclass, implement your own construct() method. When you instantiate the SwingWorker subclass, the runtime environment creates a thread but does not start it. The thread starts when you invoke start() on the object. CS3283 - Hugh Anderson s notes. Page number: 287 Example Here s an example of using SwingWorker from the tutorial - an image is to be loaded over a network (given a URL). This may of course take quite a while, so we don t block our main thread - (if we did this, the GUI may freeze). CS3283 - Hugh Anderson s notes. Page number: 288

SwingWorker example CODE LISTING ImageLoader.java private void loadimage(final String imagepath, final int index) { final SwingWorker worker = new SwingWorker() { ImageIcon icon = null; public Object construct() { icon = new ImageIcon(getURL(imagePath)); return icon; public void finished() { Photo pic = (Photo)pictures.elementAt(index); pic.seticon(icon); if (index == current) updatephotograph(index, pic); ; worker.start(); CS3283 - Hugh Anderson s notes. Page number: 289 Timer The Timer class is used to repeatedly perform an operation. When you create a Timer, you specify its frequency, and you specify which object is the listener for its events. Once you start the timer, the action listener s actionperformed() method will be called for each event. CS3283 - Hugh Anderson s notes. Page number: 290

Event dispatching thread The event-dispatching thread is the main event-handling thread. It is normal for all GUI code to be called from this main thread, even if some of the code may take a long time to run. However - we have already mentioned that we should not delay the event-dispatching thread. Swing provides a solution to this - the InvokeLater() method may be used to safely run code in the event-dispatching thread. CS3283 - Hugh Anderson s notes. Page number: 291 InvokeLater The method requests that some code be executed in the event-dispatching thread, but returns immediately, without waiting for the code to execute. Runnable doworkrunnable = new Runnable() { public void run() { dowork(); ; SwingUtilities.invokeLater(doWorkRunnable); CS3283 - Hugh Anderson s notes. Page number: 292

Handling events Actions associated with Java/Swing components raise events - moving the mouse or clicking a JButton all cause events to be raised. The application program writes a listener method to process an event, and registers it as an event listener on the event source. There are different kinds of events, and we use different kinds of listener to act on them. CS3283 - Hugh Anderson s notes. Page number: 293 Listener types Action Button click A window closes Mouse click Mouse moves Component becomes visible Keyboard focus List selection changes Listener type ActionListener WindowListener MouseListener MouseMotionListener ComponentListener FocusListener ListSelectionListener CS3283 - Hugh Anderson s notes. Page number: 294

Listeners The listener methods are passed an event object which gives information about the event and identifies the event source. CS3283 - Hugh Anderson s notes. Page number: 295 Event handlers When you write an event handler, you must do the following: Specify a class Register an instance of the class as a listener Implement the methods CS3283 - Hugh Anderson s notes. Page number: 296

Specify class Specify a class that either implements a listener interface or extends a class that implements a listener interface. public class MyClass implements ActionListener {... CS3283 - Hugh Anderson s notes. Page number: 297 Register it Register an instance of the class as a listener upon the components. Component.addActionListener(instanceOfMyClass); CS3283 - Hugh Anderson s notes. Page number: 298

Implement method Implements the methods in the listener interface. public void actionperformed(actionevent e) {...//code that reacts to the action... CS3283 - Hugh Anderson s notes. Page number: 299 Event handling Make sure that your event handler code executes quickly, or your program may seem to be slow. In the sample code given so far, we have used window listeners to react if someone closes a window, but not to capture other sorts of events. CS3283 - Hugh Anderson s notes. Page number: 300

Handling events CODE LISTING CheckBoxDemo.java public class frame.setcontentpane CheckBoxDemo extends (new CheckBoxDemo JPanel ()); { frame.pack (); JCheckBox frame.setvisible chinbutton; (true); JCheckBox glassesbutton; StringBuffer choices; JLabel pic; public CheckBoxDemo () { chinbutton = new JCheckBox ("Chin"); glassesbutton = new JCheckBox ("Glasses"); CheckBoxListener mylistener = new CheckBoxListener (); chinbutton.additemlistener (mylistener); glassesbutton.additemlistener (mylistener); choices = new StringBuffer (" ht"); pic = new JLabel (new ImageIcon ("geek " + choices.tostring () + ".gif")); pic.settooltiptext (choices.tostring ()); JPanel checkpanel = new JPanel (); checkpanel.setlayout (new GridLayout (0, 1)); checkpanel.add (chinbutton); checkpanel.add (glassesbutton); setlayout (new BorderLayout ()); add (checkpanel, BorderLayout.WEST); add (pic, BorderLayout.CENTER); setborder (BorderFactory.createEmptyBorder (20, 20, 20, 20)); class CheckBoxListener implements ItemListener { public void itemstatechanged (ItemEvent e) { int index = 0; char c = ; Object source = e.getitemselectable (); if (source == chinbutton) { index = 0; c = c ; else if (source == glassesbutton) { index = 1; c = g ; if (e.getstatechange () == ItemEvent.DESELECTED) c = ; choices.setcharat (index, c); pic.seticon (new ImageIcon ("geek " + choices.tostring () + ".gif")); pic.settooltiptext (choices.tostring ()); public static void main (String s[]) { JFrame frame = new JFrame ("CheckBoxDemo"); frame.addwindowlistener (new WindowAdapter () { public void windowclosing (WindowEvent e) { System.exit (0); ); CS3283 - Hugh Anderson s notes. Page number: 301 Example code When you change either checkbox, an itemlistener responds to the event and changes the graphic. CS3283 - Hugh Anderson s notes. Page number: 302

Summary of topics In this module, we introduced the following topics: The containment heirarchy Layout managers Menus Threading Event handling CS3283 - Hugh Anderson s notes. Page number: 303