IS311 Programming Concepts. GUI Building with Swing

Similar documents
Agenda. GUI Building with Swing ต องม พ นความร ต อไปน ก อน. Java Graphical User Interfaces. IS311 Programming Concepts

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

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

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

Introduction to the JAVA UI classes Advanced HCI IAT351

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

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

Packages: Putting Classes Together

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

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

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

Graphical User Interfaces. Comp 152

Java. GUI building with the AWT

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

GUI in Java TalentHome Solutions

Graphic User Interfaces. - GUI concepts - Swing - AWT

Window Interfaces Using Swing Objects

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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!

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

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

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

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

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

Basicsof. JavaGUI and SWING

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

Chapter 6: Graphical User Interfaces

BASICS OF GRAPHICAL APPS

Programming graphics

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

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

Window Interfaces Using Swing Objects

Swing from A to Z Some Simple Components. Preface

CHAPTER 2. Java Overview

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

Systems Programming Graphical User Interfaces

Sri Vidya College of Engineering & Technology

Graphical User Interfaces in Java - SWING

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

Chapter 12 Advanced GUIs and Graphics

CS 251 Intermediate Programming GUIs: Components and Layout

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

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

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

Laying Out Components. What is Widget Layout?

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

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

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

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

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

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

Introduction. Introduction

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

Swing. By Iqtidar Ali

Graphical User Interfaces (GUIs)

Programming Mobile Devices J2SE GUI

Java Graphical User Interfaces

Java: Graphical User Interfaces (GUI)

Part I: Learn Common Graphics Components

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

Dr. Hikmat A. M. AbdelJaber

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

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

CS11 Java. Fall Lecture 4

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

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

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

CS 2113 Software Engineering

Chapter 7: A First Look at GUI Applications

Dr. Hikmat A. M. AbdelJaber

Lecture 5: Java Graphics

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

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

Using Several Components

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

Java Programming Lecture 6

SINGLE EVENT HANDLING

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

G51PRG: Introduction to Programming Second semester Applets and graphics

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

Swing Programming Example Number 2

PIC 20A GUI with swing

Graphical User Interface (GUI)

2110: GUIS: Graphical User Interfaces

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

JAVA NOTES GRAPHICAL USER INTERFACES

Containers and Components

User interfaces and Swing

Agenda. Container and Component

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

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

Transcription:

IS311 Programming Concepts GUI Building with Swing 1

Agenda Java GUI Support AWT Swing Creating GUI Applications Layout Managers 2

ต องม พ นความร ต อไปน ก อน Classes / Objects Method Overloading Inheritance Polymorphism Interfaces How to read the Java2 API Documents 3

Java Graphical User Interfaces AWT Abstract Window Toolkit GUI for Java 1.0 and 1.1 Swing or Java Foundation Classes (JFC) Java 2 Extension to AWT 4

AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for many applications Uses the controls defined by your OS (whatever it is) therefore it's least common denominator Difficult to build an attractive GUI import java.awt.*; import java.awt.event.*; 5

Some AWT Components Java.awt package Button A graphical push button Label Displays a single line of read only text Menu A single pane of a pull-down menu MenuItem A single item within a menu TextField Displays a single line a text and allows user to enter and change the text Table Displays a list of items 6

Swing Extension to AWT Available with Java 2 and as an extension to Java 1.1 Provides more advanced components than AWT Be careful when using with Applets Not all browsers support Swing 7

Swing Components Available in the javax.swing package JButton JLabel JMenu JMenuItem JTextField JTable JSlider - Simulates a slider control JProgressBar Displays the progress of a time consuming operation 8

Advantages of Swing Swing components are implemented with absolutely no native code More portable Not restricted to least common denominator Swing buttons and labels can display images instead of, or in addition to, text You can easily add or change the borders drawn around most Swing components. For example, it's easy to put a box around the outside of a container or label. You can easily change the behavior or appearance of a Swing component by either invoking methods on it or creating a subclass of it. Swing components don't have to be rectangular. Buttons, for example, can be round. 9

Swing Components Include everything from buttons to split panes to tables Pluggable Look and Feel Support Accessibility API Enables assistive technologies such as screen readers and Braille displays to get information from the user interface Java 2D API (Java 2 Platform only) Enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and in applets Drag and Drop Support (Java 2 Platform only) Provides the ability to drag and drop between a Java application and a native application 10

Import Swing Present in all modern Java implementations (since 1.2) More controls, and they are more flexible Gives a choice of look and feel packages Much easier to build an attractive GUI import javax.swing.*; import javax.swing.event.*; and import java.awt.*; import java.awt.event.*; You may not need all of these packages 11

Swing vs. AWT Swing is built on top of AWT, so you need to import AWT and use a few things from it Swing is bigger and slower Swing is more flexible and better looking Swing and AWT are incompatible--you can use either, but you can t mix them ความจร งสามารถใช ผสมก นได แต ไม ควรทำ Basic controls are practically the same in both AWT: Button b = new Button ("OK"); Swing: JButton b = new JButton("OK"); Swing gives far more options for everything (buttons with pictures on them, etc.) 12

To build a GUI... 1. Make somewhere to display things (a Container) Usually you would use a JFrame or a JApplet 2. Create some Components (buttons, text areas, panels, etc.) It s usually best to declare Components as instance variables, and Define them in your applet s init() method or in some application method 3. Add your Components to your display area Choose a layout manager Add your Components to your JFrame or JApplet according to the rules for your layout manager 4. Attach Listeners to your Components Interacting with a Component causes an Event to occur A Listener gets a message when an interesting event occurs, and executes some code to deal with it 13

Container The Container class is an abstract subclass of Component, which has additional methods that allow other Components to be nested inside of it. Other Container objects can be stored inside of a Container (since they are themselves Components), which makes for a fully hierarchical containment system. A container can also have a layout manager that controls the visual placement of components in a container.

Containers Container JApplet JFrame JPanel JWindow The superclass of containers. Swing version of Applet A top-level window with a title, menu bar, and borders. A container that can be embedded in other containers A top-level window without a title, menu bar, or borders.

Containers and Components A GUI is built by putting components into containers The job of a Container is to hold and display Components Some frequently used types (subclasses) of Component are JButton, JCheckbox, JLabel, JTextField, and JTextArea A Container is also a Component This allows Containers to be nested Important Container classes are JFrame, JApplet, and JPanel JFrame and JApplet both contain other containers; use getcontentpane() to get to the container you want You typically create and use JPanels directly 16

Structure of a JFrame object Title JFrame JRootPane JLayeredPane optional menu bar content pane (พ นท สำหร บแสดงผล) glass pane What is a pane? pane ในความหมายท วไป หมายถ งกระจกหน งแผ นบน หน าต างหร อประต ในคอมพ วเตอร หมายถ งพ นท บนหน าต างท ใช แสดงผล Adapted from Core Java 1.2, Volume 1 - Fundamentals, Horstmann & Cornell Java top-level containers (JFrame, JApplet,...) have several layers (panes): root, content, layered, and glass. Programs normally reference only the content pane.

JTextField Example JPasswordField JButton JLabel JScrollPane JTextArea 18

Example: JButton Declaration in GUI class private JButton computebutton; computebutton = new JButton("COMPUTE"); Instantiation in GUI class constructor 19

JLabel Example: JLabel namelabel = new JLabel("Student name"); Creation in GUI class constructor since labels do not generate events 20

Example: JTextField Declaration in GUI class private JTextField namefield; namefield = new JTextField(35); Instantiation in GUI class constructor 21

Example: JPasswordField Declaration in GUI class private JPasswordField userpassfield; userpassfield = new JPasswordField(12); Instantiation in GUI class constructor 22

Example: JTextArea Declaration in GUI class private JTextArea studentarea; studentarea = new JTextArea(4,35); Instantiation in GUI class constructor 23

Creating an Application JComponent Import classes import javax.swing.*; import java.awt.*; import java.awt.event.*; All Swing components extend JComponent class Set size Change color Define fonts Hover help Before components can be displayed, they must be added to a container Containers can be placed in other Containers Layout managers arrange components JButton JButton 24

Creating an GUI Create a class that represents the GUI Serves as the container JApplet, JFrame, JWindow public class Buttons extends JFrame { Call constructor method to handle setup Set the size of the frame (in pixels) Handle window closing Display the frame 25

Adding Components to a Container Simplest container is a panel (extend JPanel) JButton quit = new JButton( Quit ); JPanel panel = new JPanel(); panel.add(quit); Other containers (ie Frames, Windows, Applets) Broken down into panes Components are added to container s content pane Quit 26

Japplet Example import javax.swing.*; public class ButtonApplet extends JApplet { JButton abort = new JButton("Abort"); JButton retry = new JButton("Retry"); JButton fail = new JButton("Fail"); } public void init() { JPanel pane = new JPanel(); pane.add(abort); pane.add(retry); pane.add(fail); setcontentpane(pane); } 27

JFrame Examle import javax.swing.*; public class Buttons extends JFrame { JButton abort = new JButton("Abort"); JButton retry = new JButton("Retry"); JButton fail = new JButton("Fail"); public Buttons() { } JPanel pane = new JPanel(); pane.add(abort); pane.add(retry); pane.add(fail); setcontentpane(pane); } public static void main(string[] args) { Buttons rb = new Buttons(); rb.show(); } Abort Retry Fail 28

Layout Management Each container has a layout manager that directs the arrangement of its components Java API has many layout managers but the most three useful layout managers are: border layout flow layout grid layout

Layout Managers LayoutManager BorderLayout CardLayout FlowLayout The interface that a layout manager must implement. place components along each edge and in center displays one component at a time places components left-to-right, top-tobottom GridBagConstraints Used to specify constraints in a GridBagLayout object. GridLayout places components in a rigid grid with fixed sized cells. GridBagLayout places components in a grid with flexible sized cells.

FlowLayout The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started.

FlowLayout Constructors public FlowLayout(int align, int hgap, int vgap) Constructs a new FlowLayout with a specified alignment, horizontal gap, and vertical gap. The gaps are the distances in pixel between components. public FlowLayout(int alignment) Constructs a new FlowLayout with a specified alignment and a default gap of five pixels for both horizontal and vertical. public FlowLayout() Constructs a new FlowLayout with a default center alignment and a default gap of five pixels for both horizontal and vertical.

GridLayout Manager GridLayout arranges components into a grid of rows and columns. You can specify the number of rows and columns, or the number of rows only and let the layout manager determine the number of columns, or the number of columns only and let the layout manager determine the number of rows. The cells in the grid are equal size. Look at the API for the add method and constructor.

GridLayout Constructors public GridLayout(int rows, int columns) Constructs a new GridLayout with the specified number of rows and columns. public GridLayout(int rows, int columns, int hgap, int vgap) Constructs a new GridLayout with the specified number of rows and columns, along with specified horizontal and vertical gaps between components.

เมท อดสำหร บ add component ลงใน container public add(component comp) เพ ม component ลงใน container ตามลำด บ public add(component comp, int index) เพ ม component ลงใน container โดยระบ ตำแหน งท ต องการเพ ม ถ าเป น -1 หมายถ งต อ ท าย 35

Border Layout A BorderLayout manager can place a component into any of five regions. Regions which are unused give up their space to BorderLayout.CENTER.

BorderLayout Demo class Border extends JFrame { JButton north = new JButton("North"); JButton south = new JButton("South"); JButton east = new JButton("East"); JButton west = new JButton("West"); JButton center = new JButton("Center"); Border() { super("border"); setsize(240, 280); JPanel pane = new JPanel(); pane.setlayout(new BorderLayout()); pane.add("north", north); pane.add("south", south); pane.add("east", east); pane.add("west", west); pane.add("center", center); setcontentpane(pane); } 37

Border Layout Example Panel innerpane North Get Data Exit Center Panel datapane JPanel pane 38

The BorderLayoutDemo class public class BorderLayoutDemo extends JFrame { static DefaultTableModel datatable = new DefaultTableModel(); static JTable table = new JTable(dataTable); static JButton exitbutton = new JButton( "Exit" ); static JPanel pane = new JPanel(); static JPanel innerpane = new JPanel(); static JPanel datapane = new JPanel(); static JButton getbutton = new JButton ("Get Data"); static JTextField inputdata = new JTextField(6); 39

The BorderLayoutDemo class pane.setlayout(new BorderLayout()); innerpane.add(getbutton); innerpane.add(inputdata); innerpane.add(exitbutton); pane.add("north",innerpane);.... JScrollPane scrollpane = new JScrollPane(table); datapane.add("center",scrollpane); pane.add("center",datapane); 40

Summary Abstract Windowing Toolkit provides GUI support for Java 1.0 and Java 1.1 Swing (Java Foundation Classes) provides GUI support for Java 2 Swing is an extension of the Java 1.1 AWT Swing components are found in the javax.swing package Layout Managers provide a consistent form for a GUI 41

Event Handling 42

Components & Events A component generates events when a user interacts with it. The Event class encapsulates all the states in an event. Each component generates a different set of events.

Event Delegation Model An event source produces events and dispatches them to all registered event listeners Stimulus Event Event Listener Event Source 44

source & listener A single class can implement multiple listener interfaces A single listener object can register with multiple event sources Multiple listener objects can register with a single event source (multicast) 45

Events An Event is the encapsulation of some user input delivered to the application asynchronously Events correspond to Physical actions, (e.g., mouse button down, key press/release) Logical events, (e.g., button press, got focus) The java.awt.awtevent is the root class of all AWT events (a subclass of java.util.eventobject) From any AWTEvent you can get the object that was the event source by invoking getsource() AWTEvent is subclassed as: ActionEvent, WindowEvent, ItemEvent, KeyEvent, MouseEvent, TextEvent, etc. 46

GUI Events Defined by Java Event Class WindowEvent ActionEvent ItemEvent ListSelection KeyEvent MouseEvent Source Object User Action A frame A button A text field A text area A menu item A combo box A checkbox A radio button A list box A key A mouse Window opened/closed Click button Press Enter Press Enter Select menu item Select/deselect item Select/deselect item Select/deselect item Select/deselect item Key pressed or released Move or click mouse 47

Event Programming and Processing Programming Steps: Create GUI component object. Add a listener for the component object. Implement event method inside an event class handler. Java Processing Steps: User action on GUI component. Event Call Listener detects Event method(s) is called event. automatically to handle event. 48

Event Listener Interfaces Event handling is achieved through the use of listener interfaces, defined in java.awt.event, e.g. ActionListener - Button, MenuItem, List WindowListener - Window ItemListener - Choice, List, Checkbox KeyListener - Component MouseListener - Commponent MouseMotionListener -Component TextListener - TextComponent 49

Event Listener Interfaces (cont.) Inheritors of the interface have to implement one or more methods in order to respond to certain types of events, e.g. ActionListener - actionperformed WindowListener - windowopen, WindowClosing, etc. 50

Event Registration Three things must be done to receive events: The object's class must inherit from an XXXListener interface Each interface requires the class to implement one or more interface (abstract) methods that receive an event and process it Prior to receiving any events, an object must register itself with the event source by invoking its addxxxlistener method 51

Event Delivery and Decoding When an event occurs, the event source sends the event to the appropriate listening methods on all registered event listeners If necessary the listener can get the event source (getsource()) from the event For ActionEvents, the action command (getactioncommand()) can also be gotten Learn about events and event processing by implementing event listener and calling System.out.println(e) in the listening methods 52

การถอน Event Listener An event listener may be removed from a component's list of listeners by calling a removexxxlistener() method, passing in the listener to be removed. eg., btn.removeactionlistener(al); removes action listener al from button btn 53

การจ ดการ Event ด วย subclass ของ component class MyBtn extends Button { public MyBtn(String label) { super(label); enableevents(awtevent.action_event_mask); } } public void processactionevent(actionevent ae) { System.out.println( "Processing an action event."); super.processactionevent(ae); } 54

Adding an ActionListener to the Bottons class abort.addactionlistener( new ActionListener() { public void actionperformed( ActionEvent event ) { ); } } System.exit(0); An ActionListener allows you to add the lines of code that will be executed when the end user clicks the button 55

IDE with Visual Editor JBuilder (Borland ขายก จการไปแล ว) Eclipse (IBM and others) http://www.eclipse.org/ Netbeans (Sun->Oracle) https://netbeans.org/ IntelliJ IDEA (JetBrains) https://www.jetbrains.com/idea/ IDE = Integrated Development Environment 56

Eclipse Visual Editor 57

Visual Programming A Visual Programming Environment 58