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

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

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

Lecture 18 Java Graphics and GUIs

CSE 331 Software Design & Implementation

Announcements. Introduction. Lecture 18 Java Graphics and GUIs. Announcements. CSE 331 Software Design and Implementation

Building Java Programs Bonus Slides

Introduction to the JAVA UI classes Advanced HCI IAT351

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

Graphical User Interfaces. Comp 152

CSE 331 Software Design & Implementation

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

Packages: Putting Classes Together

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

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!

Graphic User Interfaces. - GUI concepts - Swing - AWT

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

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

COMPSCI 230. Software Design and Construction. Swing

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

Window Interfaces Using Swing Objects

Chapter 12 GUI Basics

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

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

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphical User Interfaces

Basicsof. JavaGUI and SWING

CS 251 Intermediate Programming GUIs: Components and Layout

Systems Programming Graphical User Interfaces

SD Module-1 Advanced JAVA

Java. GUI building with the AWT

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

SD Module-1 Advanced JAVA. Assignment No. 4

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

Window Interfaces Using Swing Objects

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...

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

Swing. By Iqtidar Ali

Chapter 6: Graphical User Interfaces

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

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

Part I: Learn Common Graphics Components

CS11 Java. Fall Lecture 4

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

Java: Graphical User Interfaces (GUI)

Graphical interfaces & event-driven programming

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

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

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

Programming graphics

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved.

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

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

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.

Graphical User Interface (GUI)

Java Programming Lecture 6

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

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

Graphical User Interfaces (GUIs)

PIC 20A GUI with swing

GUI in Java TalentHome Solutions

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

Java IDE Programming-I

user-friendly and easy to use.

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

INTRODUCTION TO (GUIS)

BASICS OF GRAPHICAL APPS

CS11 Java. Fall Lecture 3

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

Chapter 12 GUI Basics. Motivations. The design of the API for Java GUI programming

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

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

Swing from A to Z Some Simple Components. Preface

Jonathan Aldrich Charlie Garrod

User interfaces and Swing

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

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

CHAPTER 2. Java Overview

Graphical User Interface

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

MIT AITI Swing Event Model Lecture 17

Chapter 12 Advanced GUIs and Graphics

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

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

Learn Java Programming, Dr.Hashamdar. Getting Started with GUI Programming

2110: GUIS: Graphical User Interfaces

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Programming Languages and Techniques (CIS120)

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

Programming Mobile Devices J2SE GUI

AP CS Unit 11: Graphics and Events

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

Graphical User Interface (GUI)

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

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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

Laying Out Components. What is Widget Layout?

Programming Languages and Techniques (CIS120e)

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

Transcription:

CSE 331 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/ 1

Why learn GUIs? Learn about event-driven programming techniques Practice learning and using a large, complex API A chance to see how it is designed and learn from it: model-view separation design patterns refactoring vs. reimplementing an ailing API Because GUIs are neat! Caution: There is way more here than you can memorize. Part of learning a large API is "letting go." You won't memorize it all; you will look things up as you need them. But you can learn the fundamental concepts and general ideas. 2

Java GUI History Abstract Windowing Toolkit(AWT): Sun's initial effort to create a set of cross-platform GUI classes. (JDK 1.0-1.1) Maps general Java code to each operating system's real GUI system. Problems: Limited to lowest common denominator; clunky to use. Swing: A newer GUI library written from the ground up that allows much more powerful graphics and GUI construction. (JDK 1.2+) Paints GUI controls itself pixel-by-pixel rather than handing off to OS. Benefits: Features; compatibility; OO design. Problem:Both exist in Java now; easy to get them mixed up; still have to use both in various places. 3

GUI terminology window: A first-class citizen of the graphical desktop. Also called a top-level container. examples: frame, dialog box, applet component: A GUI widget that resides in a window. Also called controls in many other languages. examples: button, text box, label container: A logical grouping for storing components. examples: panel, box 4

Components 5

Swing inheritance hierarchy Component (AWT) Window Frame JFrame (Swing) JDialog import java.awt.*; import javax.swing.*; Container JComponent (Swing) JButton JColorChooser JFileChooser JComboBox JLabel JList JMenuBar JOptionPane JPanel JPopupMenu JProgressBar JScrollbar JScrollPane JSlider JSpinner JSplitPane JTabbedPane JTable JToolbar JTree JTextArea JTextField... 6

Component properties Each has a get(or is) accessor and a setmodifier method. examples: getcolor, setfont, setenabled, isvisible name background border enabled focusable font foreground height, width visible tooltip text size, minimum / maximum / preferred size type Color Border boolean boolean Font Color int boolean String Dimension description background color behind component border line around component whether it can be interacted with whether key text can be typed on it font used for text in component foreground color of component component's current size in pixels whether component can be seen text shown when hovering mouse various sizes, size limits, or desired sizes that the component may take 7

JFrame a graphical window to hold other components public JFrame() public JFrame(String title) Creates a frame with an optional title. Call setvisible(true)to make a frame appear on the screen after creating it. public void add(component comp) Places the given component or container inside the frame. 8

More JFrame public void setdefaultcloseoperation(int op) Makes the frame perform the given action when it closes. Common value passed: JFrame.EXIT_ON_CLOSE If not set, the program will never exit even if the frame is closed. public void setsize(int width, int height) Gives the frame a fixed size in pixels. public void pack() Resizes the frame to fit the components inside it snugly. 9

JButton a clickable region for causing actions to occur public JButton(String text) Creates a new button with the given string as its text. public String gettext() Returns the text showing on the button. public void settext(string text) Sets button's text to be the given string. 10

GUI example import java.awt.*; // Where is the other button? import javax.swing.*; public class GuiExample1 { public static void main(string[] args) { JFrame frame = new JFrame(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(new Dimension(300, 100)); frame.settitle("a frame"); JButton button1 = new JButton(); button1.settext("i'm a button."); button1.setbackground(color.blue); frame.add(button1); JButton button2 = new JButton(); button2.settext("click me!"); button2.setbackground(color.red); frame.add(button2); } } frame.setvisible(true); 11

Sizing and positioning How does the programmer specify where each component appears, how big each component should be, and what the component should do if the window is resized / moved / maximized / etc.? Absolute positioning(c++, C#, others): Programmer specifies exact pixel coordinates of every component. "Put this button at (x=15, y=75) and make it 70x31 pxin size." Layout managers(java): Objects that decide where to position each component based on some general rules or criteria. "Put these four buttons into a 2x2 grid and put these text boxesin a horizontal flow in the south part of the frame." 12

Containers and layout Place components in a container; add the container to a frame. container:an object that stores components and governs their positions, sizes, and resizing behavior. 13

JFrame as container A JFrame is a container. Containers have these methods: public void add(component comp) public void add(component comp, Object info) Adds a component to the container, possibly giving extra information about where to place it. public void remove(component comp) public void setlayout(layoutmanager mgr) Uses the given layout manager to position components. public void validate() Refreshes the layout (if it changes after the container is onscreen). 14

Preferred sizes Swing component objects each have a certain size they would "like" to be: Just large enough to fit their contents (text, icons, etc.). This is called the preferred sizeof the component. Some types of layout managers (e.g. FlowLayout) choose to size the components inside them to the preferred size. Others (e.g. BorderLayout, GridLayout) disregard the preferred size and use some other scheme to size the components. Buttons at preferred size: Not preferred size: 15

FlowLayout public FlowLayout() treats container as a left-to-right, top-to-bottom "paragraph". Components are given preferred size, horizontally and vertically. Components are positioned in the order added. If too long, components wrap around to the next line. myframe.setlayout(new FlowLayout()); myframe.add(new JButton("Button 1")); The default layout for containers other than JFrame(seen later). 16

BorderLayout public BorderLayout() Divides container into five regions: NORTH and SOUTH regions expand to fill region horizontally, and use the component's preferred size vertically. WEST and EAST regions expand to fill region vertically, and use the component's preferred size horizontally. CENTERuses all space not occupied by others. myframe.setlayout(new BorderLayout()); myframe.add(new JButton("Button 1"), BorderLayout.NORTH); This is the default layout for a JFrame. 17

GridLayout public GridLayout(int rows, int columns) Treats container as a grid of equally-sized rows and columns. Components are given equal horizontal / vertical size, disregarding preferred size. Can specify 0 rows or columns to indicate expansion in that direction as needed. 18

Event Listeners 19

Graphical events event: An object that represents a user's interaction with a GUI component; can be "handled" to create interactive components. listener: An object that waits for events and responds to them. To handle an event, attach a listener to a component. The listener will be notified when the event occurs (e.g. button click). 20

Event-driven programming event-driven programming: A style of coding where a program's overall flow of execution is dictated by events. Rather than a central "main" method that drives execution, the program loads and waits for user input events. As each event occurs, the program runs particular code to respond. The overall flow of what code is executed is determined by the series of events that occur, not a pre-determined order. 21

Event hierarchy import java.awt.event.*; EventObject AWTEvent (AWT) ActionEvent TextEvent ComponentEvent FocusEvent WindowEvent InputEvent KeyEvent MouseEvent EventListener AWTEventListener ActionListener TextListener ComponentListener FocusListener WindowListener KeyListener MouseListener 22

Action events action event: An action that has occurred on a GUI component. The most common, general event type in Swing. Caused by: button or menu clicks, check box checking / unchecking, pressing Enter in a text field,... Represented by a class named ActionEvent Handled by objects that implement interface ActionListener 23

Implementing a listener public class name implements ActionListener { public void actionperformed(actionevent event) { code to handle the event; } } JButton and other graphical components have this method: public void addactionlistener(actionlistener al) Attaches the given listener to be notified of clicks and events that occur on this component. 24

Nested classes nested class: A class defined inside of another class. Usefulness: Nested classes are hidden from other classes (encapsulated). Nested objects can access/modify the fields of their outer object. Event listeners are often defined as nested classes inside a GUI. 25

Nested class syntax // enclosing outer class public class name {... } // nested inner class private class name {... } Only the outer class can see the nested class or make objects ofit. Each nested object is associated with the outer object that created it, so it can access/modify that outer object's methods/fields. If necessary, can refer to outer object as OuterClassName.this 26

Static inner classes // enclosing outer class public class name {... } // non-nested static inner class public static class name {... } Static inner classes are not associated with a particular outer object. They cannot see the fields of the enclosing class. Usefulness: Clients can refer to and instantiate static inner classes: Outer.Inner name = new Outer.Inner(params); 27

GUI event example public class MyGUI { private JFrame frame; private JButton stutter; private JTextField textfield; public MyGUI() {... stutter.addactionlistener(new StutterListener()); }... } // When button is clicked, doubles the field's text. private class StutterListener implements ActionListener { public void actionperformed(actionevent event) { String text = textfield.gettext(); textfield.settext(text + text); } } 28