Java Swing Reference: 1.Swing: A Beginner’s Guide by Herbt Schildt, TMH Edition.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Introduction to JFC Swing Written by Adam Carmi. Agenda About JFC and Swing Pluggable Look and Feel Swing Components Borders Layout Management Events.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
Understanding SWING Architecture CS 4170 UI Design Hrvoje Benko Oct. 9, 2001.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Contructing GUI’s in Java Implemented in the Swing API Imported into your programs by: import javax.swing.*; Most Swing programs also need the AWT packages.
Java Swing Chris North cs3724: HCI. AWT to Swing AWT: Abstract Windowing Toolkit import java.awt.* Swing: new with Java2 import javax.swing.* Extends.
CS3 - AWT/Swing1 The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness –The Abstract.
Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.
Java Programming Chapter 10 Graphical User Interfaces.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
3461A Readings from the Swing Tutorial. 3461A Overview  The follow is the Table of Contents from the trail “Creating a GUI with JFC/Swing” in the “The.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Chapter 9: Visual Programming Basics Object-Oriented Program Development Using Java: A Class-Centered Approach.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
CSCI Swing1 The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness –The Abstract.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
University of Limerick1 Software Architecture Java Layout Managers.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include: a rich set of user interface components; a.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Java Swing One of the most important features of Java is its ability to draw graphics.
Lecture # 6 Graphical User Interface(GUI). Introduction A graphical user interface (GUI) presents a user- friendly mechanism for interacting with an application.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Java Swing and Events Chris North cs3724: HCI. Presentations nadine edwards, steve terhar Vote: UI Hall of Fame/Shame?
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Introduction to Swing Mr. Crone. What is Swing? a collection of pre-made Java classes used to create a modern graphical user interface.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Module 13: Swing API Object Oriented Programming(Java)
A Quick Java Swing Tutorial
Java Swing.
Lecture 27 Creating Custom GUIs
A Quick Java Swing Tutorial
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Graphical User Interface
Presentation transcript:

Java Swing Reference: 1.Swing: A Beginner’s Guide by Herbt Schildt, TMH Edition

What is Java Swing? Swing is a collection of classes and interface that define the Java GUI. It is built upon the foundation of the AWT. AWT(Abstract Window Toolkit) defines a basic set of controls, windows, and dialog boxes that support a usable, but limited GUI. It is Part of the Oracle’s Java Foundation Classes (JFC)- an API for providing a GUI for Java programs Offers a rich set of GUI components such as buttons, text fields, scroll bars, check boxes and so on…

Swing vs AWT AWT is Java’s original set of classes for building GUIs –Translates its visual components into their corresponding, platform specific equivalents, or peers –Not truly portable: looks different and lays out inconsistently on different OSs Due to OS’s underlying display management system Swing is designed to solve AWT’s problems –Lightweight components, entirely written in Java and do not rely on platform-specific peers Uses AWTs components –Window, frame, dialog –Lays out consistently on all OSs –Uses AWT event handling mechanism

Swing features  GUI components like button, checkbox, and so on…  Java 2D API: images, figures, animation  Pluggable look and feel(PLAF): use samples (metal, Windows and Motif) or create your own  Data Transfer: cut, copy, paste, drag & drop  Internationalization: supports different input language  Accessibility API: for people with disabilities  Undo Framework API: supports unlimited numbers of actions to undo and redo  Flexible Deployment: run within a browser as an applet or Java Application

Components and Containers A Swing GUI consists of components and containers A component is an object (an independent visual control)that represents an element on the screen –e.g. label, text area, text field A container is a component that holds other components –Can nest containers inside each other –e.g. windows, frames, dialogs, and panels

Components and Containers Swing defines two types of top-level containers: 1)Heavyweight containers: JFrame, JApplet, JWindow, and JDialog - do not inherit JComponent class but inherit AWT classes. 2) Lightweight containers: Jpanel, JRootPane - do inherit JComponent class In general, we create one or more components and add them to a container to display them on the screen –JFrame consists of multiple containers (panes)

JFrame - Each top-level container define a set of panes

8 The Initial Swing GUI Containment Hierarchy File Edit Undo Redo Cut Frame / Dialog / Applet Root Pane Layered Pane Content Pane Glass Pane a 3D model enables menus to pop up above the content pane allows for interception of mouse events and painting across GUI components

 Root pane Created by Swing on realizing frame and‘Invisibly’ attached to top-level container (e.g. JFrame) The root pane manages the other panes and the (optional) menu bar. The panes that comprise the root pane are glass pane, the content pane, and the layered pane.  Glass pane It is the top level pane. It sits above and completely covers all other panes By default, it is a transparent instance of Jpanel It enables you to manage mouse events that affect the entire container  Layered pane Provided by root pane, It is an instance of JLayeredPane. The layered pane allows components to be given a depth value. It holds the content pane and the (optional) menu bar.  Content pane It is an instance of JPanel This is the pane to which you will add visual components

GUI Program Design The GUI provides a view of the program, it is clearly not the program Making the GUI code as independent of the program code is a good strategy –Changes in the program do not necessarily change the GUI –Different GUIs can be developed for the same program –Debugging and maintaining both the GUI and the program code is easier

Model-View-Controller(MVC) Design pattern often used in Swing Breaks a GUI component down into three parts –“Model” corresponds to the state information associated with a component –“View” determines how the component looks when rendered on the screen –“Controller” interprets user input, commanding the model and view to change as necessary

MVC ModelView Controller The model passes its data to the view for rendering The view determines which events Are passed to the controller The controller updates the model Based on the events received

MVC in Swing Swing often merges the View and Controller together into one object called the UI delegate. The UI delegate interprets the user’s interactions and updates the model. It also handles the display. Swing’s approach is called the Model-Delegate architecture. Because the view(look) and controller(feel) are separate from the model, the look and feel can be changed without affecting how the component is used within a program.(PLAF)

MVC in Swing Model View Controller Delegate Program Logic The Application

The MVC Power One of the best examples of MVC/Delegates in Swing is the pluggable look and feel (PLAF) PLAF enables the entire UI look to be changed by simply switching PLAF’s A simple matter of switching the delegate which draws buttons, lists, etc. Replaces AWT’s heavyweight OS-look with a controllable, lightweight one.

Building a GUI A GUI is built in layers. Bottom most layer is the window ( Container ) - usually a JFrame (for an application), or a JApplet –Contains all other components –Can provide basic features like maximise/minimise buttons, title bar, menu bar, etc On top of this, components are layered ( Component ) –Components, e.g. buttons, text fields –or intermediate containers, e.g. panels Arrangement of components in a container is handled by a layout manager –Its job is to instruct components on how to arrange themselves so the GUI is drawn correctly. Write some Listeners and attach them 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 Display your window

Steps to build a GUI There are 5 steps to creating a Java based GUI: 1.import the GUI packages 2.declare the widgets to be used in the GUI 3.add the widgets to a container 4.implement any event handling 5.show the GUI

Build from bottom up Create: Frame Panel Components Listeners Add: (bottom up) listeners into components components into panel panel into frame JPanel JButton Listener JFrame JLabel

Using a GUI Component 1.Create it Instantiate object: b = new JButton(“press me”); 2.Configure it Properties: b.text = “press me”; [avoided in java] Methods: b.setText(“press me”); 3.Add it panel.add(b); 4.Listen to it Events: Listeners JButton

A Simple Framed Window import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); frame.setVisible(true); }

Notes on the Example setSize and setLocation require java.awt.* ; the rest require javax.swing.* The JFrame constructor argument is used as a title The Dimension constructor takes an integer width and height, respectively The setLocation method takes a pair of integer coordinates (x,y) where (0,0) is the upper left corner of the display The visibility of a JFrame is set to false by default

Changing Background Color import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); Container contentPane = frame.getContentPane(); contentPane.setBackground(Color.red); frame.setVisible(true); }

Content Panes Q: Why not just: frame.setBackground(Color.red); ? Ans: In order to be lightweight, Swing's top-level window objects must be built on top of a lightweight AWT Container object introduced in version 1.1 This container is called a content pane

24 Swing Hello World import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World!"); frame.setSize(220, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); contentPane.setLayout(null); JButton button = new JButton("Hello World!"); button.setLocation(30, 30); button.setSize(150, 100); contentPane.add(button); frame.setVisible(true); }

JFrames A JFrame is a Window with a title and a border A JFrame provides the basic building block for screen- oriented applications. JFrame win = new JFrame( “title” );

Creating a JFrame import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setVisible(true); //win.show(); } } // SwingFrame

Creating a JFrame import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setSize( 250, 150 ); win.setVisible(true); //win.show(); } } // SwingFrame

JLabels Jlabel is a component that you can put text into. When creating a label you can specify the initial value and the alignment you wish to use within the label. lbl = new JLabel( ”text", JLabel.RIGHT ) ;

Hello World import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); // operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel( "Hello World" ); win.getContentPane().add( label ); win.pack(); // set frame size win.setVisible(true); //win.show(); } } // SwingFrame

JButtons JButton extends Component, displays a string and delivers an ActionEvent for each mouse click. Normally buttons are displayed with a border In addition to text, JButtons can also display icons button = new JButton( ”text“ ) ;

Buttons import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); JButton button = new JButton( "Click Me!!" ); win.getContentPane().add( button ); win.pack(); win.setVisible(true); //win.show(); } } // SwingFrame

Layout Manager –An interface that defines methods for positioning and sizing objects within a container. Java defines several default implementations of LayoutManager. Layouts allow you to format components on the screen in a platform independent way The standard JDK provides five classes that implement the LayoutManager interface: –FlowLayout –GridLayout –BorderLayout –CardLayout –GridBagLayout Layout managers are defined in the AWT package

Changing the Layout To change the layout used in a container you first need to create the layout. Then the setLayout() method is invoked on the container is used to use the new layout. The layout manager should be established before any components are added to the container JPanel p = new JPanel() ; p.setLayout( new FlowLayout() );

Layout Manager Heuristics Left to right, Top to bottom c n s ew FlowLayoutGridLayout BorderLayout none, programmer sets x,y,w,h null One at a time CardLayout GridBagLayout JButton

Code: null layout JFrame f = new JFrame(“title”); JPanel p = new JPanel( ); JButton b = new JButton(“press me”); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null);// x,y layout p.add(b); f.setContentPane(p); press me

Code: FlowLayout JFrame f = new JFrame(“title”); JPanel p = new JPanel( ); FlowLayout L = new FlowLayout( ); JButton b1 = new JButton(“press me”); JButton b2 = new JButton(“then me”); p.setLayout(L); p.add(b1); p.add(b2); f.setContentPane(p); press methen me

FlowLayout When you add components to the screen, they flow left to right (centered) based on the order added and the width of the screen. If the screen is resized, the components' flow will change based on the new width and height

Flow Layout import javax.swing.*; import java.awt.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.getContentPane().setLayout( new FlowLayout() ); for ( int i = 0; i < 10; i++ ) win.getContentPane().add( new JButton( String.valueOf( i ) ) ); win.pack(); win.setVisible(true); //win.show(); } } // SwingFrame

FlowLayout

GridLayout Arranges components in rows and columns –If the number of rows is specified columns = number of components / rows –If the number of columns is specified Rows = number of components / columns –The number of columns is ignored unless the number of rows is zero. The order in which you add components matters –Component 1  (0,0), Component 2  (0,1), …... Components are resized to fit the row-column area

GridLayout gridLayout( 2, 4 ) gridLayout( 0, 4 ) gridLayout( 4, 4 )gridLayout( 10, 10 )

BorderLayout BorderLayout provides 5 areas to hold components. These are named after the four different borders of the screen, North, South, East, West, and Center. When a Component is added to the layout, you must specify which area to place it in. The order in which components is not important. The center area will always be resized to be as large as possible

BorderLayout import javax.swing.*; import java.awt.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); Container content = win.getContentPane(); content.setLayout( new BorderLayout() ); content.add( "North", new JButton( "North" ) ); content.add( "South", new JButton( "South" ) ); content.add( "East", new JButton( "East" ) ); content.add( "West", new JButton( "West" ) ); content.add( "South", new JButton( "South" ) ); content.add( "Center", new JButton( "Center" ) ); win.pack(); win.setVisible(true); //win.show(); } } // SwingFrame

BorderLayout

Default Layout Managers The default layout manager for content panes is BorderLayout. Recall that the following Swing components have content panes: –JWindow –JFrame –JDialog –JApplet –JInternalFrame The other Swing container is the JPanel, whose default layout manager is FlowLayout.

Event Handling The Delegation Event Model: Provides a standard mechanism for a source to generate an event and send it to a set of listeners. In the delegation event model, there are three participants: 1.Event: It is an object that describes a state change in a source. –Each time a user interacts with a component an event is generated, e.g.: A button is pressed A menu item is selected A window is resized A key is pressed –An event informs the program about the action that must be performed 2.Event source : It is an object whose state changes. It generates Events. 3.Event listener: It is an object that is notified when an event occurs.

A listener receives event notifications A listener must: –Register with one or more sources for a specific type of event –Implement an interface to receive those events –Unregister if those events are not needed any longer Source Listener events container The Delegation Event Model Event Handling

Handling: –create a component e.g., a JButton –add it to the GUI e.g., to a JPanel –register a listener to be notified when the component generates an event e.g., interface ActionListener –define the callback method e.g., actionPerformed()

How to Implement an Event Handler Every event handler requires three pieces of code: 1.declaration of the event handler class that implements a listener interface or extends a class that implements a listener interface public class MyClass implements ActionListener { 2.registration of an instance of the event handler class as a listener someComponent.addActionListener(instanceOfMyClass ); 3.providing code that implements the methods in the listener interface in the event handler class public void actionPerformed(ActionEvent e) {...//code that reacts to the action... }

A Simpler Event Example public class ButtonClickExample extends JFrame implements ActionListener { JButton b = new JButton("Click me!"); public ButtonClickExample() { b.addActionListener(this); getContentPane().add(b); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { b.setBackground(Color.CYAN); } public static void main(String[] args) { new ButtonClickExample(); } 1 2 3

Event Example public class SwingApplication extends JFrame { private static String labelPrefix = "Number of button clicks: "; private int numClicks = 0; JLabel label = new JLabel(labelPrefix + "0 "); public SwingApplication(String title) { super(title); JButton button = new JButton("I'm a Swing button!"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { label.setText(labelPrefix + ++numClicks); } }); JPanel panel = new JPanel(); panel.add(button); panel.add(label); getContentPane().add(panel); pack(); setVisible(true); } public static void main(String[] args) { new SwingApplication("SwingApplication"); }}

Event Handling Options for implementing listeners: –anonymous inner classes –named inner classes –listener class