1.74k likes | 1.75k Views
Learn how to build graphical user interfaces using Java's AWT and Swing libraries. Understand components, containers, events, and frames in GUI programming. Practical examples and step-by-step guidance provided.
E N D
G. Pullaiah College of Engineering and Technology Object Oriented Programming through Java Department of Computer Science & Engineering
Unit - V • Introduction the AWT • AWT classes, • window fundamentals, • Graphics • AWT control fundamentals • Managing scroll bars • layout managers, • Menu bars and Menus, • dialog boxes • Overriding paint().
1 Overview • 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.
Swing • Java has a newer library for building graphical user interfaces, known as “Swing.” Swing is more powerful and sophisticated than the AWT. • Swing is built around the existing AWT, so it helps to understand the AWT first. • Swing is similar enough to the AWT that it’s relatively easy to switch if the need arises. • Many Swing classes correspond to AWT classes. For example, Swing’s JButton class corresponds to the AWT’s Button class.
Creating a Graphical User Interface • 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 a Graphical User Interface • 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.
Creating a Graphical User Interface • 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.
2 Frames • 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. • The DrawableFrame objects used in previous chapters are examples of frames.
The 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.
Frame Methods • 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.
Frame Methods • 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 a 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.
FrameTest.java // Displays a frame on the screen. // WARNING: Frame cannot be closed. 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); } }
Creating a Frame • Frame created by the FrameTest program: • As with the other AWT components, the appearance of a frame depends on the platform.
Creating a Frame • 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.
Setting the Location of a Frame • 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 a Frame • The Frame class is rarely used to create objects directly. • Instead, it’s customary to define a subclass of Frame and then create an instance of the subclass. • This strategy makes it possible to tailor the subclass. • In particular, the constructor for the subclass can put components into the frame.
Adding Components to a Frame • 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.
Adding Components to a Frame • 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); } }
Adding Components to a Frame • Frame created by the ButtonTest program: • Pressing the “Testing” button has no effect.
Adding Components to a Frame • 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.
Adding Components to a Frame • It’s not necessary to have two separate classes, (ButtonTest and ButtonTestFrame). • By moving the main method from ButtonTest to ButtonTestFrame, the program could be condensed to one class (ButtonTestFrame).
3 Event Listeners • When the user performs an action, Java creates an object containing information about the event. • Responding to an event is done by writing a method that can be called when the event occurs. • Steps involved in handling an event: 1. The user performs an action, causing an event to be triggered (or fired). 2. An object is created that contains information about the event, including an indication of which component was involved. 3. A method that belongs to a listener object is called. The object created in step 2 is passed to the method.
Events • 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.
Interfaces • 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(ActionEventevt); } • This resembles a class declaration, except that the word class has been replaced by interface, and the actionPerformed method has no body.
Interfaces • 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.
Interfaces • 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 Listeners • 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.
Creating Event Listeners • 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 ActionListeneractionPerformed(ActionEvent evt) AdjustmentListeneradjustmentValueChanged(AdjustmentEvent evt) ItemListeneritemStateChanged(ItemEvent evt) TextListenertextValueChanged(TextEvent evt) • Each interface contains a single method. The access modifier for each method is public, and the result type is void.
Creating Event Listeners • There’s a similar set of listener interfaces for low-level events. • The listener interface for WindowEvent is named WindowListener.
Creating Event Listeners • 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 publicvoid 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) { … } }
Creating Event Listeners • 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 Listeners • 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 Listeners • 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 Listeners • Because ButtonListener implements the ActionListener interface, the compiler can verify that it has an actionPerformed method. • The ActionListener interface acts as a sort of contract that ButtonListener agrees to honor. • It’s an error to pass an object to addActionListener unless the object belongs to a class that implements ActionListener.
Creating Event Listeners • The ButtonTest program displays a “Testing” button, but pressing the button has no effect. • Making the button work involves defining a listener class that implements the ActionListener interface, creating an instance of the class, and attaching it to the button. • 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(ActionEventevt) { System.exit(0); } }
Creating Event Listeners • Frame created by the ButtonTest2 program:
Creating Event Listeners • 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.
Adapter Classes • To make the Close button work, a WindowEvent listener is needed. • A class that implements the WindowListener interface would have to contain seven methods. • There’s an easier technique: use the WindowAdapter class from the java.awt.event package. • This class implements the WindowListener interface, although the methods that it provides are all empty.
Adapter Classes • The listener class will extend the WindowAdapter class and override the windowClosing method. • It will then inherit all the other methods it needs. • WindowAdapter is an example of an adapter class—a class that can be extended instead of implementing an interface. • Java provides matching adapter classes for most interfaces that have two or more methods.
Adapter Classes • The ButtonTest3 program is a modification of ButtonTest2. • The new WindowCloser class extends WindowAdapter and provides a windowClosing method of its own. • The constructor for ButtonTestFrame now calls addWindowListener to install a WindowCloser object as a listener for window events.
ButtonTest3.java // Displays a frame containing a single "Close window" // button. The frame can be closed by pressing either the // "Close window" button or the frame's "close" button. import java.awt.*; import java.awt.event.*; // Driver class public class ButtonTest3 { 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()); // Attach window listener addWindowListener(new WindowCloser()); } } // Listener for button class ButtonListener implements ActionListener { public void actionPerformed(ActionEventevt) { System.exit(0); } }
// Listener for window class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent evt) { System.exit(0); } }