Basicsof. JavaGUI and SWING

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

Containers and Components

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

Graphical User Interfaces. Comp 152

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

Window Interfaces Using Swing Objects

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

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

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

Graphical User Interfaces in Java - SWING

Layout. Dynamic layout, Swing and general layout strategies

Introduction to the JAVA UI classes Advanced HCI IAT351

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

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

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

Graphical User Interfaces (GUIs)

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

Window Interfaces Using Swing Objects

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!

Sri Vidya College of Engineering & Technology

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

Laying Out Components. What is Widget Layout?

Building Java Programs Bonus Slides

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

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

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Java. GUI building with the AWT

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Basics of programming 3. Java GUI and SWING

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Resizing a Window. COSC 3461: Module 5B. What is Widget Layout? Size State Transitions. What is Widget Layout? Hierarchical Widget Layout.

CS11 Java. Fall Lecture 4

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

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

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

Dr. Hikmat A. M. AbdelJaber

Graphic User Interfaces. - GUI concepts - Swing - AWT

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

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

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

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

COMPSCI 230. Software Design and Construction. Swing

Java: Graphical User Interfaces (GUI)

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

Part I: Learn Common Graphics Components

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

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

GUI in Java TalentHome Solutions

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

Chapter 6: Graphical User Interfaces

Packages: Putting Classes Together

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

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

2110: GUIS: Graphical User Interfaces

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

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

CS11 Java. Fall Lecture 3

GUI Programming. Chapter. A Fresh Graduate s Guide to Software Development Tools and Technologies

What is Widget Layout? COSC 3461 User Interfaces. Hierarchical Widget Layout. Resizing a Window. Module 5 Laying Out Components

Systems Programming Graphical User Interfaces

Top-Level Containers

Chapter 14. More Swing

Programming Mobile Devices J2SE GUI

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

Graphical User Interfaces

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

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

Layout. Dynamic layout Layout design pattern Layout strategies

No SVN checkout today. Object-Oriented Design

CS 251 Intermediate Programming GUIs: Components and Layout

Layout. Dynamic layout Layout design pattern Layout strategies. 2.6 Layout 2

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

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

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

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

News and info. Array. Feedback. Lab 4 is due this week. It should be easy to change the size of the game grid.

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

Java Programming Lecture 6

Agenda. Container and Component

INTRODUCTION TO (GUIS)

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

PIC 20A GUI with swing

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

Lecture 18 Java Graphics and GUIs

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

Chapter 12 Advanced GUIs and Graphics

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

Jonathan Aldrich Charlie Garrod

Programming graphics

Graphical User Interface (GUI)

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

Summary Chapter 25 GUI Components: Part 2

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

CSC 161 SPRING 17 LAB 2-1 BORDERLAYOUT, GRIDLAYOUT, AND EVENT HANDLING

SWING - GROUPLAYOUT CLASS

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

Transcription:

Basicsof programming3 JavaGUI and SWING

GUI basics Basics of programming 3 BME IIT, Goldschmidt Balázs 2

GUI basics Mostly window-based applications Typically based on widgets small parts (buttons, scrollbars, etc) built on a windowing framework Abundance of frameworks AWT, SWING, SWT, etc Logic is to be defined GUI builders help Basics of programming 3 BME IIT, Goldschmidt Balázs 3

Abstract Windowing Toolkit Heavy-weight widgets relies on OS features Abstract facade same look and feel on all platforms Different implementations incompatibility issues Most features still in use events, layoutmanagement, etc java.awt.* Basics of programming 3 BME IIT, Goldschmidt Balázs 4

SWING Rich set of GUI elements light-weight widgets implemented in Java Heavy use of model-view-controller pattern complex widgets have separate model classes parts of rendering is implemented separately Configurable look and feel via new classes, config files and config parameters javax.swing.* Basics of programming 3 BME IIT, Goldschmidt Balázs 5

Basic window architecture JFrame JMenuBar JMenu JMenuItem JSplitPane JPanel JButton JButton JPanel JTextField Basics of programming 3 BME IIT, Goldschmidt Balázs 6

Window Application Lifecycle Build up window create JFrame or other window put on containers and components Register event handlers separate objects for handling user events Make it visible window is shown and can be used Useit Close window release resources Basics of programming 3 BME IIT, Goldschmidt Balázs 7

Components and containers Basics of programming 3 BME IIT, Goldschmidt Balázs 8

Components and containers Basic widgets JButton JTextField JPanel JFrame Complex widgets MVC JList + JScrollPane Basics of programming 3 BME IIT, Goldschmidt Balázs 9

Widget basics Rendering is automatic Common functionality size (minimum, maximum, preferred) visibility enabled/disabled event handling Can be added to a container Containers are also widgets component-hierarchy Basics of programming 3 BME IIT, Goldschmidt Balázs 10

Simple widgets: JButton Classic button can be clicked event handling later Text and image can be set Size is calculated automatically shrinks and grows as the container asks Important methods setenabled(boolean) get/settext() Basics of programming 3 BME IIT, Goldschmidt Balázs 11

Simple widgets: JTextField Classic textfield textual input can be entered Initial text and size can be set Size is calculated automatically if needed shrinks and grows as the container asks Important methods seteditable(boolean) get/settext(string) setcaretposition(int) setselectionstart/end(int) Basics of programming 3 BME IIT, Goldschmidt Balázs 12

Simple widgets: JPanel Basic container components can be put on it Responsible for layout of components Size is calculated automatically if needed shrinks and grows as the parent container asks Important methods add(component[, param]) setlayout(layoutmanager) getcomponentat(int,int) Basics of programming 3 BME IIT, Goldschmidt Balázs 13

Basic window: JFrame Basic window with frame and title All window operations are supported some has to be explicitly enabled Size is calculated automatically based on the size of its contents Important methods add(component, int where) pack() setvisible(boolean) setdefaultcloseoperation(jframe.exit_on_close) Basics of programming 3 BME IIT, Goldschmidt Balázs 14

Example: building a GUI JFrame f = new JFrame( Swing Example ); JPanel p = new JPanel(); JButton b = new JButton( Click Me! ); JTextField t = new JTextField( Type here! ); p.add(b); p.add(t); f.add(p, BorderLayout.NORTH); f.pack(); f.setdefaultcloseoperation(f.exit_on_close); f.setvisible(true); Basics of programming 3 BME IIT, Goldschmidt Balázs 15

Event handling Basics of programming 3 BME IIT, Goldschmidt Balázs 16

Event handling basics Listener (observer) pattern two roles: listener and subject subject receives event...... and forwards it to all registered listeners single event handler thread for all events Event types for all kinds of events java.util.eventobject java.awt.awtevent java.awt.event.mouseevent java.awt.event.windowevent Events and listeners can be separated responsibility can be dedicated Basics of programming 3 BME IIT, Goldschmidt Balázs 17

Event handling interfaces XEVent XListener interface (implementation is needed) implementation has to be registered at the component addxlistener(xlistener el) XEvent must be processed MouseEvent, KeyEvent, AdjustmentEvent, FocusEvent stb. it is usual to use anonymous inner classes looks convenient but is hardly maintainable Basics of programming 3 BME IIT, Goldschmidt Balázs 18

Event handling adapters XAdapter default implementation of XListener empty methods convenience class if only a subset of methods is to be implemented use them for a clearer looking code consider single inheritance! Basics of programming 3 BME IIT, Goldschmidt Balázs 19

Event handling example Modify previous example: when pressing button, put current time in textfield! An ActionListener implementation is needed new class, take care of visibility actionperformed(actionevent ae) method How to identify the button ActionEvent s getsource Component ActionEvent s getactioncommand String name of button or set by setactioncommand(string c) Basics of programming 3 BME IIT, Goldschmidt Balázs 20

Event handling example final class MyActionListener implements ActionListener { JTextField t; public MyActionListener(JTextField tt) { t = tt;} public void actionperformed(actionevent ae) { if (ae.getactioncommand().equals("date")) { t.settext((new Date()).toString()); } } }... JButton b = new JButton("Click Me!"); b.setactioncommand("date"); ActionListener al = new MyActionListener(t); b.addactionlistener(al);... Basics of programming 3 BME IIT, Goldschmidt Balázs 21

Layout handling Basics of programming 3 BME IIT, Goldschmidt Balázs 22

Where are components placed? Problems positioning this page is optimized for 800x600 resolution what happens when resizing Solution: Layout Managers every container has a default layout manager layout maganers can be changed (setlayoutmanager) responsible for placement recursive calculation when resizing recalculation occurs Basics of programming 3 BME IIT, Goldschmidt Balázs 23

Layout Managers Container void setlayout(layoutmanager mgr) LayoutManager getlayout() void validate() recalculates placement and arranges components (recursive) Component add(component comp [,int index]) void add(component c, Object constraint, int index) adds the component to the container optional parameter specifies special placement demands LayoutManager long story... Basics of programming 3 BME IIT, Goldschmidt Balázs 24

BorderLayout North West Center East South Five fields north, south, west, east, center Default layout for JFrames Resize in the arrows direction possible One field one component Basics of programming 3 BME IIT, Goldschmidt Balázs 25

FlowLayout C1 C2 C3 Default layout for JPanel Puts components beside each other if there is no more place, starts new row Does not resize them individually Direction depends on container ComponentOrientation.LEFT_TO_RIGHT, RIGHT_TO_LEFT Alignment can be set: LEFT, RIGHT, CENTER, LEADING, TRAILING Basics of programming 3 BME IIT, Goldschmidt Balázs 26

CardLayout Components are placed below each other like a deck of cards one comoponent one card Always the topmost is visible Deck can be reordered by methods of the managers Components can be named for faster access Basics of programming 3 BME IIT, Goldschmidt Balázs 27

GridLayout C1 C2 C3 C4 C5 C6 C7 C8 Components are put into an NxM grid Every component has the same size resize if needed Direction depends on the container LEFT_TO_RIGHT RIGHT_TO_LEFT If number of rows is fixed, new columns can be added Basics of programming 3 BME IIT, Goldschmidt Balázs 28

GridBagLayout C1 C2 C3 C4 C5 C6 C7 C8 Advanced variant of GridLayout Components can occupy more than one square GridBagConstraint specifies occupancy rules Basics of programming 3 BME IIT, Goldschmidt Balázs 29

BoxLayout C1 C2 C3 Vertical or horizontal placement of components No new line when full Four kinds of directions X_AXIS Y_AXIS: horizontal or vertical LINE_AXIS PAGE_AXIS: considers also ComponentOrientation Basics of programming 3 BME IIT, Goldschmidt Balázs 30

SpringLayout For flexible table-like layout Basically the connection between components edges must be defined Only for GUI builders (designers) hard to program manually Basics of programming 3 BME IIT, Goldschmidt Balázs 31

GroupLayout Independent specification of horizontal and vertical dimensions each component is added twice Hierarchical: groups are placed into each other Sequential or parallel placement Replacing a component: void replace(component oldc, Component newc) Basics of programming 3 BME IIT, Goldschmidt Balázs 32

GroupLayout (swing) 2 vertical horizontal Basics of programming 3 BME IIT, Goldschmidt Balázs 33

GroupLayout (swing) 3 layout.sethorizontalgroup(layout.createsequentialgroup().addcomponent(label).addgroup(layout.createparallelgroup(leading).addcomponent(textfield).addgroup(layout.createsequentialgroup().addgroup(layout.createparallelgroup(leading).addcomponent(casecheckbox).addcomponent(wholecheckbox)).addgroup(layout.createparallelgroup(leading).addcomponent(wrapcheckbox).addcomponent(backcheckbox)))).addgroup(layout.createparallelgroup(leading).addcomponent(findbutton).addcomponent(cancelbutton)) ); Basics of programming 3 BME IIT, Goldschmidt Balázs 34

GroupLayout (swing) 4 layout.setverticalgroup(layout.createsequentialgroup().addgroup(layout.createparallelgroup(baseline).addcomponent(label).addcomponent(textfield).addcomponent(findbutton)).addgroup(layout.createparallelgroup(leading).addgroup(layout.createsequentialgroup().addgroup(layout.createparallelgroup(baseline).addcomponent(casecheckbox).addcomponent(wrapcheckbox)).addgroup(layout.createparallelgroup(baseline).addcomponent(wholecheckbox).addcomponent(backcheckbox))).addcomponent(cancelbutton))) ); Basics of programming 3 BME IIT, Goldschmidt Balázs 35

BorderLayoutviaGroupLayout North West Center East South Basics of programming 3 BME IIT, Goldschmidt Balázs 36

BorderviaGroup step1 GroupLayout layout = new GroupLayout(getContentPane()); getcontentpane().setlayout(layout); layout.setautocreategaps(true); layout.setautocreatecontainergaps(true); layout.sethorizontalgroup (layout.createparallelgroup(center).addcomponent(north).addgroup(layout.createsequentialgroup().addcomponent(west).addcomponent(center).addcomponent(east) ).addcomponent(south) ); Software technology BME IIT, Goldschmidt Balázs 37

BorderviaGroup step2 layout.setverticalgroup (layout.createsequentialgroup().addcomponent(north).addgroup(layout.createparallelgroup(center).addcomponent(west).addcomponent(center).addcomponent(east) ).addcomponent(south) ); layout.linksize(swingconstants.vertical, north, south); layout.linksize(swingconstants.horizontal, west, east); Software technology BME IIT, Goldschmidt Balázs 38

Inner classes Defined within a class outside or inside methods as a parameter when calling a method (nasty!!!) No limit on nesting Has access to members of nesting class methods final parameters and final local variables only Goal: encapsulation e.g. small helper class in a big one: Map Map.Entry Basics of programming 3 BME IIT, Goldschmidt Balázs 39

Member class has a name can be accessed outside of nesting class depending on visibility declared in class block (not inside a method) class In1 { int k; class In2 {int x = k;} } void bar() { } In2 i2 = new In2(); k = i2.x++;... In1 i1 = new In1(); i1.k++; In1.In2 i3 = new In1().new In2();... Objektumorientált SW-tervezés BME IIT, Goldschmidt Balázs 40

Local class has name declared inside a block used in the block public class Test { void bar() { int i = 10; k = i++; void xxx() { i++; } xxx(); void foo(final int a) { } class In1 { } int k = a; In1 i1 = new In1(); int j = i; i1.j++; } } Objektumorientált SW-tervezés BME IIT, Goldschmidt Balázs 41

Combined example public class Test { int i = 10; void xxx() { i++; } void foo(final int a) { class In1 { int k = a; int j = i; class In2 { int x = k; int y = i; int z = a; } } } void bar() { In2 i2 = new In2(); k = i2.z++; xxx(); } } In1 i1 = new In1(); i1.j++; In1.In2 i3 = new In1().new In2(); Objektumorientált SW-tervezés BME IIT, Goldschmidt Balázs 42

Anonymousclass never abstract, never static, always final has no declared constructor public class MyFrame extends JFrame { MyFrame() { super("myframe"); addwindowlistener(new WindowListener() { public void windowclosing(windowevent e) { System.ext(0); }... // other methods } ); } } Objektumorientált SW-tervezés BME IIT, Goldschmidt Balázs 43