Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 CHAPTER-1 SWING JAVA-GUI

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

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

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

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

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

7 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

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

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

10 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

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

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

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

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

15 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); }

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

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

18 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

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

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

21 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); }

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

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

24 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

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

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

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

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

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

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

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

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

33 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

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

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

36 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) { … }

37 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();

38 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());

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

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

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

42 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); }

43 // 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); }

44 Frame created by the ButtonTest2 program:

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

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

47 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

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

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

50 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

51 /* */ 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(); }

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

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

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

55 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

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

57 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

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

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

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

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

62 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”

63 MVC architecture

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

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

66 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


Download ppt "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."

Similar presentations


Ads by Google