CHAPTER-1 SWING JAVA-GUI. HERE ARE SOME TERMS THAT YOU’LL ENCOUNTER IN YOUR LESSON ON GRAPHICS: AWT Swing Applet/JApplet Graphics object init() GUI.

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
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.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 16 Applets.
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 14 Applets, Images,
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L05 (Chapter 16) Applets.
Introduction to Java Swing “We are the sultans of swing” – Mark Knopfler.
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Applets Chapter 17.  Java’s big splash onto the scene came in the mid 90’s. The people at Sun Microsystems had managed to work java programs into Web.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
JAPPLET.
Learn about the types of Graphics that are available Develop a basic Graphics applet Develop a basic Graphics application Review the Java API and use.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Introduction to Applets Course Lecture Slides 29 th July 2010.
Chapter One An Introduction to Visual Basic 2010 Programming with Microsoft Visual Basic th Edition.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
– 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 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
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.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
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.
Topics Introduction Scene Graphs
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Chapter 14 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
Object Oriented Programming.  Interface  Event Handling.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Creating a Java Application and Applet
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lesson 28: More on the GUI button, frame and actions.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 Applets Programming. Introduction Java programs are divided into two main categories, applets and applications. An application is an ordinary Java program.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
CSC 205 Programming II Lecture 5 AWT - I.
Welcome To java
Aum Amriteshwaryai Namah
A First Look at GUI Applications
Lecture 09 Applets.
Abstract Window ToolKit (AWT)
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
UNIT-5.
Java Applets.
Constructors, GUI’s(Using Swing) and ActionListner
GUI building with the AWT
Graphical User Interface
Presentation transcript:

CHAPTER-1 SWING JAVA-GUI

HERE ARE SOME TERMS THAT YOU’LL ENCOUNTER IN YOUR LESSON ON GRAPHICS: AWT Swing Applet/JApplet Graphics object init() GUI

Graphics  Graphics can be simple or complex, but they are just data like a text document or sound.  Java is very good at graphics, especially for the web and small devices like phones.

JAVA Graphics  Java can write applications or applets, as you know by now.  It can make graphics in either one, and has two libraries to do it with:  Swing (the newer kind) or AWT (Abstract Windowing Toolkit, the older kind).

AWT Java’s Abstract Window Toolkit provides classes and other tools for building programs that have a graphical user interface. The term “Abstract” refers to the AWT’s ability to run on multiple platforms. Building a GUI involves creating “abstract” components such as buttons and windows, which are then mapped to “concrete” components for a specific platform.

GUI GUI programming in Java is based on three concepts:  Components. A component is an object that the user can see on the screen and—in most cases—interact with.  Containers. A container is a component that can hold other components.  Events. An event is an action triggered by the user, such as a key press or mouse click. Designing a graphical user interface involves creating components, putting them into containers, and arranging for the program to respond to events.

Creating Component Components are objects, so they’re created by invoking a constructor. A button would be created by using a constructor belonging to the Button class. The most commonly used constructor has one argument (the button’s label): Button b = new Button("Testing"); For a component to be visible, it must be added to a container (typically a frame) by the add method

GUI To detect when an event occurs, a special “listener” object can be attached to a component. When the user performs an action that involves the component, a method belonging to the listener object will be called automatically.

Frames in JAVA In Java terminology, a frame is a window with a title and a border. A frame may also have a menu bar. Frames play an important role in the AWT because a GUI program normally displays a frame when it’s executed.

Frame class Frames are created using one of the constructors in the Frame class. One constructor takes a single argument (the title to be displayed at the top of the frame): Frame f = new Frame("Title goes here"); Although the Frame object now exists, it’s not visible on the screen. Before making the frame visible, a method should be called to set the size of the frame. If desired, the frame’s location can also be specified

Frame Methods Many methods used with Frame objects are inherited from Window ( Frame ’s superclass) or from Component ( Window ’s superclass). The setSize method sets the width and height of a frame: f.setSize(width, height); If a program fails to call setSize or pack before displaying a frame, it will assume a default size.

The size of a frame can change during the execution of a program. The getSize method returns a frame’s current width and height: Dimension frameSize = f.getSize(); frameSize.width will contain f ’s width. frameSize.height will contain f ’s height.

The setVisible method controls whether or not a frame is currently visible on the screen. Calling setVisible with true as the argument makes a frame visible: f.setVisible(true); Calling it with false as the argument makes the frame disappear from the screen: f.setVisible(false); The Frame object still exists; it can be made to reappear later by calling setVisible again.

Creating Frame The FrameTest program creates a Frame object and displays it on the screen. This program illustrates three key steps: 1. Using the Frame constructor to create a frame. 2. Setting the size of the frame. 3. Displaying the frame on the screen.

import java.awt.*; public class FrameTest { public static void main(String[] args) { Frame f = new Frame("Frame Test"); f.setSize(150, 100); f.setVisible(true); }

Frame created by the FrameTest program: As with the other AWT components, the appearance of a frame depends on the platform.

Clicking on the Close button has no effect, because there’s no action associated with that button. The frame will have be closed the hard way, by killing the program. In Windows, click on the DOS window from which the program was launched, hold down the Ctrl key, and press the letter C.

Frame location By default, all windows (including frames) are displayed in the upper-left corner of the screen, which has coordinates (0, 0). The setLocation method can be used to specify a different location: f.setLocation(50, 75); To find the current location of a frame, call getLocation : Point frameLocation = f.getLocation(); The coordinates of f ’s upper-left corner will be stored in frameLocation.x and frameLocation.y

Adding components To add a component to a frame (or any kind of container), the add method is used. add belongs to the Container class, so it’s inherited by Frame and the other container classes. An example of adding a button to a frame: Button b = new Button("Testing"); add(b); These statements would normally go in the constructor for the frame class.

ButtonTest is a modified version of FrameTest. ButtonTest defines a subclass of Frame named ButtonTestFrame, and then creates an instance of ButtonTestFrame. Actions taken by the ButtonTestFrame constructor: 1. Invokes the superclass constructor (the constructor for Frame ), passing it the title of the frame. 2. Calls setLayout to specify how the components inside the frame will be laid out. 3. Creates a Button object. 4. Calls add to add the button to the frame.

ButtonTest.java // Displays a frame containing a single button. // WARNING: Frame cannot be closed. import java.awt.*; // Driver class public class ButtonTest { public static void main(String[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); } // Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setLayout(new FlowLayout()); Button b = new Button("Testing"); add(b); }

Frame created by the ButtonTest program: Pressing the “Testing” button has no effect.

Instead of calling setSize, the main method in ButtonTest could have called pack : f.pack(); pack makes the frame just large enough to display the components within it: Regardless of whether setSize or pack is called, the user can manually resize the frame.

Event Delegation model Java automatically generates event objects when Mouse or button clicked Menu, checkbox, or text selected Keyboard typed Scrollbar adjusted ….. It is up to the programmer to decide whether to do anything or what to do when an event happens

Contd… Event source:  An object that generates events Listener:  Receives events and decides what to do Event Listener Event Source Event Object evt

Contd. A listener must be registered with an event source in order to listen for events produced there.  An event source can have multiple listeners and vice versa  A listener class must implement a listener interface, which decides the response to an event.

When an event occurs, an object is created that contains information about the event. This object will belong to one of several different classes, depending on the nature of the event. These classes all belong to the java.awt.event package. Java divides events into two groups: “high-level” events and “low-level” events.

Events High-level events: Class Name Description of Event ActionEvent A significant action has been performed on a component (a button was pressed, a list item was double-clicked, or the Enter key was pressed in a text field). AdjustmentEvent The state of an adjustable component (such as a scrollbar) has changed. ItemEvent An item has been selected (or deselected) within a checkbox, choice menu, or list. TextEvent The contents of a text area or text field have changed.

Events Low-level events include moving the mouse or pressing a key. One low-level event is WindowEvent, which occurs when the status of a window has changed. In particular, a WindowEvent occurs when the user attempts to close a window.

Interface Event-handling requires the use of interfaces. An interface looks like a class, except that its methods aren’t fully defined. Each method in an interface has a name, a parameter list, and a result type, but no body. One common interface is named ActionListener : public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent evt); } This resembles a class declaration, except that the word class has been replaced by interface, and the actionPerformed method has no body.

Interface An interface is nothing but a pattern that will be used later to define “real” classes. A class implements an interface by agreeing to provide bodies for all methods in the interface. A class that implements the ActionListener interface would have to provide a method named actionPerformed with one parameter of type ActionEvent and a result type of void.

Interface The keyword implements is used to tell the compiler that a class will implement a particular interface. A class that implements the ActionListener interface: class class-name implements ActionListener { public void actionPerformed(ActionEvent evt) { … } … // Variables, constructors, and methods, // if desired } The class may contain any number of variables, constructors, and methods.

Creating Event Listener To handle an event, it’s necessary to create an event listener object. This object will be “registered” with a component; when an event occurs that involves the component, one of the listener’s methods will be called. An event listener will be an instance of a “listener class” defined by the programmer

Event Listener A listener class must implement one of the interfaces that belong to the java.awt.event package. Listener interfaces for high-level events: Interface Name Required Method ActionListener actionPerformed(ActionEvent evt) AdjustmentListener adjustmentValueChanged(AdjustmentEvent evt) ItemListener itemStateChanged(ItemEvent evt) TextListener textValueChanged(TextEvent evt) Each interface contains a single method. The access modifier for each method is public, and the result type is void.

Contd. There’s a similar set of listener interfaces for low- level events. The listener interface for WindowEvent is named WindowListener.

Creating Event Listener Pressing a button is an action event, so the listener class for a button would need to implement the ActionListener interface. To implement this interface, the class must define a public void method named actionPerformed with a parameter of type ActionEvent. An example of a listener for an action event: class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { … }

After writing a listener class, the next step is to create an instance of the class and connect it to a particular component. In the simplest case, a single listener object will be attached to a single component. Suppose that b is a Button object: Button b = new Button("Change Color"); A listener object can be created by using the constructor for the listener class: ButtonListener listener = new ButtonListener();

Creating event listener listener can now be registered as an action listener for the button: b.addActionListener(listener); It’s sometimes possible to save a statement by combining the creation of the listener object with the call of addActionListener : b.addActionListener(new ButtonListener());

Creating event listener Calling addActionListener creates a link between the Button object and its listener: When the user presses the button, the ButtonListener object’s actionPerformed method will be called.

Creating event listener Because ButtonListener implements the ActionListener interface, the compiler can verify that it has an actionPerformed method. It’s an error to pass an object to addActionListener unless the object belongs to a class that implements ActionListener.

The ButtonTest program displays a “Testing” button, but pressing the button has no effect The ButtonTest2 program is similar to ButtonTest, but the window will close when the button is pressed. Changes are highlighted in bold.

ButtonTest2.java Displays a frame containing a single "Close window" // button. The frame can be closed by pressing the button. import java.awt.*; import java.awt.event.*; // Driver class public class ButtonTest2 { public static void main(String[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); }

// Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setLayout(new FlowLayout()); Button b = new Button("Close window"); add(b); b.addActionListener(new ButtonListener()); } // Listener for button class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { System.exit(0); }

Frame created by the ButtonTest2 program:

Pressing the “Close window” button causes a call of the actionPerformed method for the button’s listener object. This method calls System.exit, which causes the program to terminate and the frame to disappear. When a program terminates, any windows that it created are automatically closed.

Applet Applet is a Java program executed by a browser. applet is an Internet application. Applets are event driven and window-based. The event is forwarded by the AWT GUI environment (graphics environment) to the applet. The applet takes the event, do some action and return the control back to AWT.

Applications Vs. Applets FeatureApplicationApplet main() methodPresentNot present ExecutionRequires JRERequires a browser Nature Called as stand-alone application as application can be executed from command prompt Requires some third party tool help like a browser to execute Restrictions Can access any data or software available on the system cannot access any thing on the system except browser’s services Security Does not require any security Requires highest security for the system as they are untrusted

java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet

Applet Life Cycle init This method is like a constructor. It is called by the browser (or applet viewer) to inform the applet that it has been loaded into the system. start This method is called after the init method. It is also called after the page has been maximized or revisited. The purpose of the method is to inform the applet that it should start executing. Since the start method can be called more than once and the init method is called only once, any code that you want to execute only once should be put in init. On the other hand, you should place in start the code that you want to execute every time a user visits the page containing your applet.

stop method is called when the user changes pages, when the page is minimized, and just before the applet is destroyed. It is called by the browser (or applet viewer) to inform the applet to stop executing destroy method is called by the browser or the applet viewer to inform the applet that it is being destroyed and that it should release any resources that it has allocated

/* */ import java.applet.Applet; import java.awt.*; public class LifeCycle extends Applet { String output = ""; String event; public void init() { event = "Initializing..."; printOutput(); } public void start() { event = "Starting..."; printOutput(); }

public void stop() { event = "Stopping..."; printOutput(); } public void destroy() { event = "Destroying..."; printOutput(); } private void printOutput() { System.out.println(event); output += event; repaint(); }

public void paint(Graphics g) { g.drawString(output, 10, 10); } Compile and run the applet: > javac LifeCycle.java > appletviewer LifeCycle.java O/p: Initializing... Starting... Stopping... Starting... Stopping... Starting... Stopping... Destroying...

import java.applet.*; import java.awt.*; public class Main extends Applet { public void paint(Graphics g) { g.drawString("Welcome in Java Applet.",40,20); } }

Advantages of Applets Execution of applets is easy in a Web browser and does not require any installation or deployment procedure in real time programming (where as servlets require). Writing and displaying (just opening in a browser) graphics and animations is easier than applications. In GUI development, constructor, size of frame, etc. are not required (but are required in applications).constructorsize of frame

Disadvantages Applets are treated as untrusted because they are developed by somebody and placed on some unknown Web server. When downloaded, they may harm the system resources or steal passwords and valuable information available on the system Take a lot of downloading time.

Swing Provides a rich set of GUI components Used to create a Java program with a graphical user interface (GUI) table controls, list controls, tree controls, buttons, and labels, and so on… Java 2D API: images, figures, animation Pluggable look and feel: use samples or create your own Data Transfer: cut, copy, paste, drag & drop Internationalization: supports different input language, right to left reading Accessibility API: for people with disabilities

AWT vs. Swing 1- Swing is also called as JFC’s (Java Foundation classes) and AWT stands for Abstract windows toolkit. 2- AWT components are called Heavyweight component and Swings are called light weight component because swing components sits on the top of AWT components and do the work. 3- Swing components require javax.swing package where as AWT components require java.awt package.

4- swings components are made in purely java and they are platform independent whereas AWT components are platform dependent. 5- we can have different look and feel in Swing whereas this feature is not supported in AWT. 6- AWT is a thin layer of code on top of the OS, whereas Swing is much larger. Swing also has very much richer functionality AWT use of native peers which creates platform specific limitations. Some components may not function at all on some platforms. Swing use pure java design. So, solve most of portability problems.

JFC Library addition to java.awt package. Contains pure java classes so provides portability. Features:  Light weight components, utilize minimum resources  Speed is fast compared to AWT components.  Offers pluggable look & feel. Means change look & feel according to requirement of platform.  Rich set of components.  Does not replace AWT, but provides extension to it.

JFC packages javax.swing javax.swing.plaf java.awt.dnd javax.accessibility Java.awt.geom

MVC Architectural design pattern which works to separate data and UI for a more cohesive and modularized system Model represents the data model  “Manages behavior and data of the application domain” View represents the screen(s) shown to the user  “Manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application” Controller represents interactions from the user that changes the data and the view  “Interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate”

MVC architecture

Goal of MVC architecture is to separate allication object (model), its representation to user (view) and way it is controlled by user (controller). Separation of view & model in MVC architecture has several advantages: 1) Multiple views using same model. Ex: same employee data in different views. 2) Efficient Modularity: Ex: create component in one platform & view in another platform. 3) Easy support for new clients. Ex: integrating ne with old one.

Window Panes Free area of window where some text or componenet can be displayed. Types of window panes: The glass pane  Represents first pane, very close to monitor screen.  Getglasspane() The layered pane  Serves to position its contents, which consist of the content pane and the optional menu bar. Can also hold other components in a specified Z order..

The content pane  The container of the root pane's visible components, excluding the menu bar.. The optional menu bar  The home for the root pane's container's menus. If the container has a menu bar, you generally use the container's setJMenuBar method to put the menu bar in the appropriate place