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

Similar documents
Introduction to the JAVA UI classes Advanced HCI IAT351

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphic User Interfaces. - GUI concepts - Swing - AWT

Introduction p. 1 JFC Architecture p. 5 Introduction to JFC p. 7 The JFC 1.2 Extension p. 8 Swing p. 9 Drag and Drop p. 16 Accessibility p.

CS 251 Intermediate Programming GUIs: Components and Layout

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

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

Packages: Putting Classes Together

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

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

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

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

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

BASICS OF GRAPHICAL APPS

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

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

Swing. By Iqtidar Ali

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

Graphical User Interface (GUI)

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

CS111: PROGRAMMING LANGUAGE II

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

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

Graphical User Interfaces. Comp 152

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

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

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

Java: Graphical User Interfaces (GUI)

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

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

Programming graphics

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert

Graphical User Interface (GUI)

Summary Chapter 25 GUI Components: Part 2

Graphical Applications

Chapter 12 GUI Basics

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

Chapter 6: Graphical User Interfaces

CS11 Java. Fall Lecture 4

Java IDE Programming-I

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

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

Java Swing Introduction

SD Module-1 Advanced JAVA

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

SD Module-1 Advanced JAVA. Assignment No. 4

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Swing Programming Example Number 2

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

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

Java Programming Lecture 6

Object-Oriented Programming in Java

Graphical User Interface (GUI)

Sri Vidya College of Engineering & Technology

Jonathan Aldrich Charlie Garrod

Window Interfaces Using Swing Objects

PIC 20A GUI with swing

(Incomplete) History of GUIs

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

G51PRG: Introduction to Programming Second semester Applets and graphics

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

Part I: Learn Common Graphics Components

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

Graphical User Interfaces (GUIs)

1.00 Lecture 14. Lecture Preview

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Graphical interfaces & event-driven programming

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

core 2 Basic Swing GUI Controls in Java 2

core programming Basic Swing GUI Controls in Java Marty Hall, Larry Brown

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

1. Swing Note: Most of the stuff stolen from or from the jdk documentation. Most programs are modified or written by me. This section explains the

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS

Widgets. Widgets Widget Toolkits. User Interface Widget

Outline CSE 3461 F10. What is a Widget? Properties of Widgets. A self-contained screen object Also called a control Examples of widgets:

Class 14: Introduction to the Swing Toolkit

Window Interfaces Using Swing Objects

Introduction to concurrency and GUIs

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

Swing. Component overview. Java UI, summer semester 2017/2018 1

GUI Components: Part 1

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Unit 6: Graphical User Interface

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

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

Chapter 17 Creating User Interfaces

Computer Science 210: Data Structures. Intro to Java Graphics

This page intentionally left blank

Event Driven Programming

Graphical User Interface (GUI)

WIMP Elements. GUI goo. What is WIMP?

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

JLayeredPane. Depth Constants in JLayeredPane

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

CS 4300 Computer Graphics

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Transcription:

Advanced Java Programming Swing Eran Werner, Tel-Aviv University Summer, 2005 19 May 2005 Advanced Java Programming, Summer 2005 1 Introduction to Swing The Swing package is part of the Java Foundation Classes (JFC), a group of features for GUI design. Other JFC features are Accessibility API, Java 2D API, Drag-and-Drop Support and Internationalization. 19 May 2005 Advanced Java Programming, Summer 2005 2 Swing libraries All Swing components are under javax.swing.* Since Swing uses the AWT event model, we need to add the following in order to use events: java.awt.* Java.awt.event.* 19 May 2005 Advanced Java Programming, Summer 2005 3 1

Swing vs. AWT Almost every AWT component has a corresponding Swing component with a J prefix (Button JButton, Panel JPanel). 19 May 2005 Advanced Java Programming, Summer 2005 4 Swing Vs. AWT Lightweight components, platform independent. 19 May 2005 Advanced Java Programming, Summer 2005 5 Swing Vs. AWT The main difference between AWT and Swing components is that swing components are implemented with absolutely no native code. Swing components aren t restricted to the features presented in every platform and therefore can have more functionality. 19 May 2005 Advanced Java Programming, Summer 2005 6 2

Swing Vs. AWT Swing Buttons and labels can display images as well as text. You can add or change the borders for swing components. You can easily change the behavior or a swing component by subclassing it or invoking its methods 19 May 2005 Advanced Java Programming, Summer 2005 7 Swing Vs. AWT Swing components do not have to be rectangular, since they can be transparent. Buttons for example can be round. The Swing API allows you to specify which look and feel to use, in contrast to AWT where the native platform look and feel is always used. 19 May 2005 Advanced Java Programming, Summer 2005 8 Swing Vs. AWT Swing components use models to keep the state. A Jslider uses BoundedRangeModel. A JTable uses a TableModel. Models are set up automatically so you don t have to bother them unless you want to take advantage of them. 19 May 2005 Advanced Java Programming, Summer 2005 9 3

Top-level container Every program with a Swing GUI must have at least one top-level container. There are three top-level containers: JFrame: a main window JDialog: a secondary window, dependent on another window. JApplet: An applet display area within a browser window. 19 May 2005 Advanced Java Programming, Summer 2005 10 JFrame Setting up a frame: JFrame frame = new JFrame("HelloWorldSwing"); //... Add components to the frame frame.pack(); frame.setvisible(true); Adding a component to a frame: frame.getcontentpane().add(label); Closing a frame: frame.setdefaultcloseoperation(jframe.exit_on_close); 19 May 2005 Advanced Java Programming, Summer 2005 11 JLabel A component that displays text. Can also display an image. Does not react to input events. Cannot get the keyboard focus. JLabel label = new JLabel("Hello World"); frame.getcontentpane().add(label); 19 May 2005 Advanced Java Programming, Summer 2005 12 4

The JComponent Class All Swing components whose names begin with "J" descend from the JComponent (except JFrame and JDialog top level containers). For example, JPanel, JScrollPane, JButton, and JTable. JComponent extends java.awt.container 19 May 2005 Advanced Java Programming, Summer 2005 13 The JComponent Class JComponent Features Tool tips Painting and borders Application-wide pluggable look and feel Support for drag and drop Double buffering Key bindings 19 May 2005 Advanced Java Programming, Summer 2005 14 Look and Feel Java (cross-platform) look and feel CDE/Motif look and feel Windows look and feel Specifying look and feel UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); 19 May 2005 Advanced Java Programming, Summer 2005 15 5

Example 1: Swing Application Topics: Dynamic text. Borders. 19 May 2005 Advanced Java Programming, Summer 2005 16 Dynamic text Creating a button The mnemonic functions as a hot key. The event handler updates the label s text when the button is clicked. JButton button = new JButton("I'm a Swing button!"); button.setmnemonic('i'); button.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { numclicks++; label.settext(labelprefix + numclicks); } }); 19 May 2005 Advanced Java Programming, Summer 2005 17 Borders Every JComponent can have one or more borders. Borders are incredibly useful objects that, while not themselves components, know how to draw the edges of Swing components. 19 May 2005 Advanced Java Programming, Summer 2005 18 6

Borders To put a border around a JComponent, you use its setborder method. You can use the BorderFactory class to create most of the borders that Swing provides. panel.setborder (BorderFactory.createEmptyBorder(30, //top 30, //left 10, //bottom 30)); //right 19 May 2005 Advanced Java Programming, Summer 2005 19 Example 2: Celsius Converter Topics: The JTextField component. The default button. Adding HTML. Icons. 19 May 2005 Advanced Java Programming, Summer 2005 20 JTextField Allows the editing of a single line of text. Fires TextEvents when changed (notifies a TextListener). JTextField temprature = new JTextField(5); The argument 5 together with the current font determines the preferred size of the text field. This argument has no effect on the amount of characters that can be typed. Event handler for the convert button: public void actionperformed(actionevent event) { int newtemp = (int)((double.parsedouble(temprature.gettext())) * 1.8 + 32); fahrenheitlabel.settext(newtemp + " Fahrenheit"); } 19 May 2005 Advanced Java Programming, Summer 2005 21 7

The default button At most one button in a top-level container can be the default button. The default button is highlighted and acts clicked when the user presses enter. Useful in Dialog windows. The default button is set in the following way (assuming we are in the constructor of a toplevel container): getrootpane().setdefaultbutton(setbutton); 19 May 2005 Advanced Java Programming, Summer 2005 22 Adding HTML To add HTML to a component, use the <html> </html> tag. HTML is useful for controlling fonts, colors, line breaks, etc. if (tempfahr <= 32) { fahrenheitlabel.settext("<html><font color=blue>" + tempfahr + "&#176 Fahrenheit </font></html>"); } else { fahrenheitlabel.settext("<html><font color=red>" + tempfahr + "&#176 Fahrenheit </font></html>"); } 19 May 2005 Advanced Java Programming, Summer 2005 23 Icons An icon usually refers to a descriptive fixed-size image. Some components can be decorated with an icon. Swing provides an interface called Icon. It also provides a useful implementation of this interface: ImageIcon. 19 May 2005 Advanced Java Programming, Summer 2005 24 8

Icons ImageIcon constructs an icon from a GIF or JPEG image. The following code adds the arrow icon to the convert button: ImageIcon icon = new ImageIcon("images/convert.gif", "Convert temperature"); JButton convertbutton = new JButton(icon); 19 May 2005 Advanced Java Programming, Summer 2005 25 Example 3: Lunar Phases The JPanel component. Compound borders. The JComboBox component. Using multiple images. 19 May 2005 Advanced Java Programming, Summer 2005 26 JPanel A general-purpose container (without a window). A panel is opaque by default. To make it transparent, use setopaque(false). A transparent panel has no background (components under it show through). The Lunar Phase example uses several panels: selectpanel = new JPanel(); displaypanel = new JPanel(); mainpanel = new JPanel(); mainpanel.setlayout(new GridLayout(2,1,5,5)); mainpanel.setborder(borderfactory.createemptyborder(5,5,5,5)); mainpanel.add(selectpanel); // using the default FlowLayout mainpanel.add(displaypanel); 19 May 2005 Advanced Java Programming, Summer 2005 27 9

Compound borders It is possible to set more than one border to a component. we can specify an outer and inner borders by BorderFactory.createCompoundBorder selectpanel.setborder(borderfactory.createcompoundborder( BorderFactory.createTitledBorder("Select Phase"), BorderFactory.createEmptyBorder(5,5,5,5))); The titled border adds a title and a border line to the component. The empty border in this case adds a space between the titled border and the inner components. 19 May 2005 Advanced Java Programming, Summer 2005 28 JComboBox A component that enables user choice. Can be editable allowing to dynamically add choices. Constructed with an array of Strings. Icons can also be added. An initial item can be selected using the setselectedindex method. The selection is done by the item index. When the user starts writing an item the selection changes accordingly. 19 May 2005 Advanced Java Programming, Summer 2005 29 JComboBox String[] phases = { "New", "Waxing Crescent, "First Quarter", "Waxing Gibbous", "Full", "Waning Gibbous", "Third Quarter", "Waning Crescent }; JComboBox phasechoices = new JComboBox(phases); phasechoices.setselectedindex(start_index); An event handler for ActionEvents fired from a combo box. public void actionperformed(actionevent event) { if ("comboboxchanged". equals(event.getactioncommand())) phaseiconlabel.seticon( images[phasechoices.getselectedindex()]); } } 19 May 2005 Advanced Java Programming, Summer 2005 30 10

Using multiple images In the Lunar Phase example, we have a bank of 8 images, but display only one at a time. We can choose whether to load all images in advance, or to load a single image when it is required ( lazy image loading ). 19 May 2005 Advanced Java Programming, Summer 2005 31 Loading Images The following code loads the images in advance: ImageIcon[] images = new ImageIcon[NUM_IMAGES]; for (int i = 0; i < NUM_IMAGES; i++) { String imagename = "images/image" + i + ".jpg"; URL iconurl = ClassLoader.getSystemResource(imageName); images[i] = new ImageIcon(iconURL); } ClassLoader.getSystemResource(imageName) searches for the image file in the classpath. A URL object with the file s location is returned. This way, we don t have to specify the full path of the images. 19 May 2005 Advanced Java Programming, Summer 2005 32 Example 4: Vote Dialog Topics: The JRadioButton component. Dialogs. Displaying and customizing dialogs. Receiving user input from a dialog. 19 May 2005 Advanced Java Programming, Summer 2005 33 11

JRadioButton An item that can be selected or deselected. For each group of radio buttons, you need to create a ButtonGroup instance and add each radio button to it. ButtonGroup takes care of unselecting the previously selected button when the user selects another one in the group. 19 May 2005 Advanced Java Programming, Summer 2005 34 JRadioButton JRadioButton[] radiobuttons = new JRadioButton[numButtons]; ButtonGroup group = new ButtonGroup(); radiobuttons[0] = new JRadioButton("<html>Candidate 1: <font color=red>sparky the Dog</font></html>"); radiobuttons[0].setactioncommand(candidate1_string); radiobuttons[1] = new JRadioButton("<html>Candidate 2: <font color=green>shady Sadie</font></html>"); radiobuttons[1].setactioncommand(candidate2_string);... for (int i = 0; i < numbuttons; i++) group.add(radiobuttons[i]); radiobuttons[0].setselected(true); 19 May 2005 Advanced Java Programming, Summer 2005 35 Dialogs A top-level window with a title and a border. used to get some input from the user. Must have a frame or another dialog as its owner. When the owner is destroyed, so is the dialog. When the owner is minimized, so is the dialog. Can be modal (disables all input to other toplevel windows). Can be used to create a custom dialog (many ready made dialogs are available in JOptionPane). 19 May 2005 Advanced Java Programming, Summer 2005 36 12

JOptionPane Enables creation and customization of several kinds of modal dialogs. Dialogs are created by invoking one of the static creation methods in JOptionPane Customization options: Choosing an icon. Setting the title and text. Setting the button text. 19 May 2005 Advanced Java Programming, Summer 2005 37 showmessagedialog Displays a modal dialog with one button labeled ok. The title, text and icon are customizable. JOptionPane.showMessageDialog (frame,"this candidate is a dog. " + "Invalid vote."); 19 May 2005 Advanced Java Programming, Summer 2005 38 showoptiondialog Displays a modal dialog with specified buttons, title, text and icon. Object[] options = {"Yes!", "No, I'll pass", "Well, if I must"}; int n = JOptionPane.showOptionDialog( frame, // the owner frame "Duke is a cartoon mascot... \n, // message text "A Follow-up Question", // title JOptionPane.YES_NO_CANCEL_OPTION, // button format JOptionPane.QUESTION_MESSAGE, // message type null, // custom icon options, // button names options[2]); // default selection 19 May 2005 Advanced Java Programming, Summer 2005 39 13

User input from a dialog The showmessagedialog and showoptiondialog methods both return an integer indicating the user s choice. The possible returned values are: YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION (dialog closed without clicking a button) The value is returned according to the clicked button and the button format of the dialog (DEFAULT, YES_NO, YES_NO_CANCEL, OK). The buttons text doesn t affect the returned value. 19 May 2005 Advanced Java Programming, Summer 2005 40 Swing components The rest of this presentation contains a short description of most Swing components: General-purpose containers. Special-purpose containers. Basic controls. Uneditable information displays. Editable displays of formatted information. 19 May 2005 Advanced Java Programming, Summer 2005 41 General-purpose containers Panel Scroll pane Split pane Tabbed pane Tool bar 19 May 2005 Advanced Java Programming, Summer 2005 42 14

Special-purpose containers Internal frame Layered pane 19 May 2005 Advanced Java Programming, Summer 2005 43 The Root pane Root pane: Created automatically by every top-level (and internal) container. Contains a Layered pane. Layered pane: Holds components in a specified depth order. Initially contains the Content pane and the optional Menu bar. Content pane: Contains all the Root pane s visible components (excluding the Menu bar). Glass pane: A hidden panel that intercepts input events for the Root pane. Can be made visible and drawn on by implementing its paint() method. 19 May 2005 Advanced Java Programming, Summer 2005 44 Basic controls Buttons Combo box List Menu Slider Text fields 19 May 2005 Advanced Java Programming, Summer 2005 45 15

Buttons The following list contains all button types (all are subclasses of AbstractButton): JButton: a common button. JCheckBox: a check box button. JRadioButton: one of a group of radio buttons. JMenuItem: an item in a menu. JCheckBoxMenuItem: a menu item that has a check box. JRadioButtonMenuItem: a menu item that has a radio button. JToggleButton: a two-state button. 19 May 2005 Advanced Java Programming, Summer 2005 46 Menus 19 May 2005 Advanced Java Programming, Summer 2005 47 Text components 19 May 2005 Advanced Java Programming, Summer 2005 48 16

Documents All Swing components separate their data (or model) from the view of the data. Text components use a Document as their model: Contains the text itself (including style info). Provides support for editing the text. Notifies document listeners on changes to the text. 19 May 2005 Advanced Java Programming, Summer 2005 49 Editor kits Each text component holds an editor kit: Manages editing actions (cut, paste, etc) for the text component. Reads and writes documents of a particular format. DefaultEditorKit: Reads and writes plain text. Provides a basic set of editing commands. The super class of all other editor kits. StyledEditorKit: Reads and writes styled text. Provides editing commands for styled text. HTMLEditorKit: Reads, writes and edits HTML. Subclass of StyledEditorKit. 19 May 2005 Advanced Java Programming, Summer 2005 50 Uneditable information displays Label Progress bar Tool tip 19 May 2005 Advanced Java Programming, Summer 2005 51 17

Editable displays of formatted information Color chooser File chooser Table Tree 19 May 2005 Advanced Java Programming, Summer 2005 52 Component becomes visible Table or list selection changes GUI events Examples of Events and Their Associated Event Listeners Action that Results in the Event Clicking a button Pressing enter while typing in a text field Choosing a menu item Closing a frame (main window) Clicking a mouse button while the cursor is over a component Moving the mouse over a component Component gets the keyboard focus Listener Type ActionListener WindowListener MouseListener MouseMotionListener ComponentListener FocusListener ListSelectionListener 19 May 2005 Advanced Java Programming, Summer 2005 53 Converting AWT to Swing java.awt.* javax.swing.* in applets, change java.applet.applet JApplet. Replace components (e.g. Button JButton). frame.add( ) frame.getcontentpane().add( ). The same for setlayout( ). Put custom painting code in paintcomponent( ) instead of paint() and update(). Custom painting in a top-level container is not visible in Swing (the painting is hidden by the content pane). Transfer the painting to another component. Thread safety issues: AWT is thread safety, while Swing is not. 19 May 2005 Advanced Java Programming, Summer 2005 54 18

Converting AWT to Swing The containment hierarchy for any window or applet containing swing components must have a swing top level container at the root of the hierarchy. For example the main window should be a JFrame rather than a Frame. 19 May 2005 Advanced Java Programming, Summer 2005 55 Thread safety: the problems Swing GUI components are updated in an event dispatching mechanism In Swing, once a component is created, it can be updated only through the event dispatching mechanism. Problem 1: What happens if we want to update the GUI from another thread? 19 May 2005 Advanced Java Programming, Summer 2005 56 Thread safety: the problems Problem2: when a button is clicked, the following actions occur one after the other: The button s GUI is drawn as pressed The button s listeners are notified on the press. The button s GUI is drawn as released Suppose that one of the listeners changes the appearance of the button. When all listeners finished, the button is redrawn (as released ) and the appearance changes may be erased. 19 May 2005 Advanced Java Programming, Summer 2005 57 19

Thread safety: the solution The SwingUtilities class provides two methods that solve the problems: invokelater: this method adds some code to the event dispatching queue. This code will be executed in its turn. The code is defined in a Runnable object. invokeandwait: like invokelater, but this method waits for the code to be executed, and only then it returns. 19 May 2005 Advanced Java Programming, Summer 2005 58 20