Download presentation
Presentation is loading. Please wait.
1
GUI and Event-Handling Programming
2
Chapter Topics: Event-driven programming Graphical user interfaces
The three parts of a GUI GUI components Containers The Abstract Windowing Toolkit (AWT) How the AWT relates to Swing Swing class hierarchy
3
Introduction to GUI programming
This module introduces: Graphical User Interface (GUI) programming. Users interact with modern application programs using graphical components such as: windows, buttons, text boxes, menus and other several components.
4
User Interfaces Some of the GUI objects from the javax.swing package
5
1.1 Simple GUI I/O with JOptionPane
Implemented by using the JOptionPane class For example: JOptionPane.showMessageDialog(null,”I love Java"); Figure: A simple “message” dialog created by the how MessageDialog method by using the JOptionPane class.
6
Simple GUI I/O with JOptionPane
In a GUI environment, there are basically two types of windows: a general-purpose frame and a special-purpose dialog. In Java, we use a JFrame object for a frame window and JDialog object for a dialog.
7
Simple GUI I/O with JOptionPane
Refer: The first argument is a frame object that controls this dialog The second argument is the text to display. In the example statement, we pass null,a reserved word, meaning there is no frame object. If we pass null as the first argument, the dialog appears on the center of the screen. If we pass a frame object, then the dialog is positioned at the center of the frame. Run the ShowMessageDialog class and confirm this behavior. JOptionPane.showMessageDialog(null,”I love Java");
8
Simple GUI I/O with JOptionPane
You get JOptionPane.showMessageDialog(jFrame, "How are you?");
9
Simple GUI I/O with JOptionPane
You get For comple sample program compile and run the sample program ShowMessageDialog.java provided JOptionPane.showMessageDialog(null, "Good Bye");
10
Simple GUI I/O with JOptionPane
Use special character sequence \n to display multiple lines of text. For example: Gives JOptionPane.showMessageDialog(null, "one\ntwo\nthree"); Figure: A dialog with multiple lines of text.
11
Simple GUI I/O with JOptionPane
The JOptionPane class can be used for input by using its showInputDialog method. For example: Gives JOptionPane.showInputDialog(null, "Enter text:"); Figure: An input dialog
12
Simple GUI I/O with JOptionPane
To assign the name input to an input string, we write The JOptionPane supports only a string input To input numerical value, you need to perform String conversion String input; input = JOptionPane.showInputDialog(null, "Enter text:");
13
Simple GUI I/O with JOptionPane
To input an integer value, say, age, we can write the code as follows: Use corresponding wrapper classes to convert the string input to other numerical data values. String str; Str = JOptionPane.showInputDialog(null, "Enter age:"); int age = Integer.parseInt(str);
14
Simple GUI I/O with JOptionPane
The table below lists common wrapper classes and their corresponding conversion methods.
15
Swing and the AWT Graphical User Interface (GUI) is implemented by using the classes from the standard javax.swing and java.awt packages. There are two sets of GUI components in Java: Components from Abstract Windowing Toolkit Components from Swing
16
Swing and the AWT Before Java 2 SDK 1.2, there was only AWT classes
Later on came the so called Swing classes AWT classes are still available, but it is generally preferable to use Swing classes.
17
Swing and the AWT The Swing class is preferred:
Component from Swing are not platform specific, Thus they have same look and accross all platforms Component from AWT are platform specific Thus their look and feel behave differently with different platforms
18
Lightweight VS Heavy weigth GUI components
GUI components that are tied on the local platform are called heavy weight components. These type of components rely heavily on the platforms’ windowing system to determine their functionalty and their look-and-feel. Those components that are not tied to the local platforms are reffered as lightweight components. Most AWT components are in heavy weight and most of those from Swing are in lightweight category
19
Event A GUI application program contains several graphical components. The user controls the application by interacting with the graphical components, doing things such as: Clicking on a button to choose a program option. Making a choice from a menu. Entering text in a text field. Dragging a scroll bar. An action such as clicking on a button is called an event.
20
event-driven programming
When you perform an action on a graphical component you generate an event. In event-driven programming the program responds to these events. The order of the events is determined by the user, not the program. This is different from programs where user interaction is done through the console. In these programs, prompts are written to the console, and the user responds to the prompts. The order of the prompts is determined by the program.
21
Responding to Events A user interacts with a GUI application by causing events. Each time the user interacts with a component, an event is sent to the application. Different events are sent to different parts of the application. An application usually ignores events that are not relevant to its purpose.
22
Responding to Events
23
Three Parts of a GUI Program
A GUI program has three parts: Graphical Components …that make up the Graphical User Interface. Listener methods …that receive the events and respond to them. Application methods …that do useful work for the user
24
Three Parts of a GUI Program
The graphical components are Swing objects. You usually extend them to make them fit your application. Listener methods are Java methods that you write. They respond to events by calling application methods. Application methods are Java methods that receive data from the GUI and send data to the GUI to be displayed.
25
Three Parts of a GUI Program
Example: Your Web browser has components (such as the "back" and "forward" buttons), listener methods that receive events (such as a click on the "back" button) and application methods that do useful things (such as moving backward or forward one page).
26
Real-world Interfaces
Non-software devices usually have user interfaces, too. They have: Components that make up the user interface. Knobs, buttons, switches, dials, lights, levers, pedals... Parts that are connected to the interface components. These "translate" user actions into something the rest of the device can act on. Parts of the device that does the actual work. Motors, gears, axles, tubes, wires, valves...
27
Container A container is an object that can hold other GUI components.
In Java terminology, a window is a container. Buttons, sliders, icons and other GUI components are always put in container.
28
Java Classes (review) The component classes that make up the AWT and Swing are related to each other by inheritance. The class Object defines the basic nature of all Java objects. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
29
AWT Hierarchy The Java AWT contains the fundamental classes used for constructing GUIs. The abstract Component class is the base class for the AWT. Some of the AWT classes derived from Component are Button, Canvas, and Container. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
30
AWT Hierarchy The diagram shows how the classes of the AWT and Swing fit together. Refer back to it occasionally as you read these notes. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
31
AWT Hierarchy The JComponent class is derived from Container and is one of the base classes of Swing. The JFrame class is derived from the AWT Frame class. It is usually the main container for a GUI application. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
32
AWT Hierarchy The JApplet class is derived from the AWT Applet class and is used for modern applets. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
33
JComponent class Objects of classes based on Container have common characteristics. They contain objects, they can be displayed on the monitor, The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
34
JComponent class They generate events, and they register event listeners. Since all Swing classes have Container as an ancestor, all Swing objects have these characteristics. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
35
JFrame A JFrame represents the window of a GUI application program.
It can hold the components and methods that your application needs. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
36
JFrame Chapter Topics: The JFrame class. Methods include the:
setSize() method. setBounds() method. setVisible() method. setDefaultCloseOperation() Extending the JFrame class The JLabel class. The diagram shows that the classes Boolean, Character, Component, String, and many others have Object as a direct ancestor.
37
Frames In java Frames == Windows
What you usually call a "window" Java calls a "frame". A frame is a container object, so GUI components can be placed in it. Like all software objects, a frame object holds information and methods. GUI application programs are usually organized around one or more frames.
38
Small GUI Program Our first GUI program does not have a listener nor any application code, and is not a useful program.
39
Small GUI Program JFrame frame = new JFrame("Test Frame 1");
Frames can created in two ways: By creating objects of frames JFrame frame = new JFrame("Test Frame 1"); By extending (inheriting) the Jframe class MyFrame extends Jframe{ }
40
Small GUI Program Let us see a complete program Jframes Methds:
frame.setSize(200,100); setTitle(); frame.setVisible( true ); setBounds() frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
41
Small GUI Program import java.awt.*; import javax.swing.*;
public class TestFrame1 { public static void main ( String[] args ) { JFrame frame = new JFrame("Test Frame 1"); frame.setSize(200,100); frame.setVisible( true ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } }
42
JFrame frame = new JFrame("Test Frame 1");
Small GUI Program First a JFrame is created by invoking its constuctor. The argument to the constructor sets the title of the frame. JFrame frame = new JFrame("Test Frame 1");
43
frame.setSize(200,100); Small GUI Program
The setSize(200,100) method makes the rectangular area 200 pixels wide by 100 pixels high. The default size of a frame is 0 by 0 pixels. frame.setSize(200,100);
44
frame.setVisible( true );
Small GUI Program The setVisible(true) method makes the frame appear on the screen. If you forget to do this, the frame object will exist as an object in memory, but no picture will appear on the screen. A call to setVisible(false) makes the frame invisible, but does not destroy the software object. frame.setVisible( true );
45
Small GUI Program The setDefaultCloseOperation() method picks the action to perform when the "close" button of the frame is clicked. This is the little X button at the top right of the frame. If you forget to call this method with the appropriate constant, a click on the close button will be ignored. frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
46
Running the GUI Program
Save Compile Run On running, the program displays an empty frame. While the program is running, you can click on the frame and drag it around, you can minimize it, you can grab a border and resize it, and so on. All of this is built into the JFrame class. Your program gets all of these features when it constructs a JFrame object. The frame remains "alive", even though there is nothing explicit in the program to keep it running. To stop the program, click on the "close button"
47
Picture of the Frame When the main() method executes, it asks the system to create a JFrame object (with new). The variable frame refers to that object, so the object's methods can be called.
48
Picture of the Frame The Java system keeps the frame active, even after the main() method has ended. The user can click on the frame, drag it on the monitor, resize it, and do all the usual things.
49
setBounds() method The setBounds() method not only specifies the size of the frame, but the location of the upper left corner: public void setBounds(int x, int y, int width, int height) This puts the upper left corner at location (x, y), where x the the number of pixels from the left of the screen and y is is the number from the top of the screen. height and width are as before.
50
setBounds() method public void setBounds(150, 250, 300, 200)
51
setDefaultCloseOperation()
It is used to specify one of several options for the close button. Use one of the following constants to specify your choice: JFrame.EXIT_ON_CLOSE — Exit the application. JFrame.HIDE_ON_CLOSE — Hide the frame, but keep the application running. (This is a default constant) JFrame.DISPOSE_ON_CLOSE — Dispose of the frame object, but keep the application running. JFrame.DO_NOTHING_ON_CLOSE — Ignore the click.
52
Layout Manager When you add() buttons (and other components) to a container, a layout manager automatically decides the size and the position of the component. The layout manager is like a little artist inside the computer. You say what components you want and the layout manager lays them out in the picture.
53
setLayout() Method There are mainly Four layouts manager: FlowLayout
BorderLayout GridLayout CardLayout
54
The FlowLayout Manager
The FlowLayout manager puts components into the frame row by row in the order they are added The FlowLayout manager is part of the java.awt package setLayout( new FlowLayout() ); // set the layout manager
55
Setting the Layout Manager
The program constructs a FlowLayout manager and then sets it using the setLayout() method of the frame. This is done before any components are added to the frame. Its argument is the an object of the used layout manager setLayout( new FlowLayout() );
56
Add() method To add the components use the method add() from the Jframe object: JLabel label1= JLabel(“Label”); JFrame frame = new JFrame("Test Frame 1"); frame.setLayout(new FlowLayout()); frame.add(label1);
57
Complete with Component method
import java.awt.*; import javax.swing.*; public class TestFrame2 { public static void main ( String[] args ) { JLabel label1=new JLabel("Button1"); JTextField textfied1=new JTextField(20); JFrame frame = new JFrame("Test Frame 2"); frame.setLayout(new FlowLayout()); frame.add(label1); frame.add(textfied1); frame.setSize(400,200); frame.setVisible( true ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } }
58
Complete with Component method
59
Extending the JFrame Class
To write a GUI application, extend the JFrame class. Add GUI components to the extended class. See a program that does that.
60
class MyFrame extends Jframe {
JPanel panel; JLabel label; MyFrame( String title ) { super( title ); setSize( 150, 100 ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new FlowLayout() ); label = new JLabel("Hello Swing!"); add( label );} }
61
Extending the JFrame Class
The MyFrame is based on JFrame. Exactly how a container arranges the components it contains is determined by a layout manager. class MyFrame extends Jframe{ //codes comes here }
62
Extending the JFrame Class
The frame holds a GUI component, a JLabel which displays the words "Hello Swing!" . The JLabel is added to the frame using the add() method. label = new JLabel("Hello Swing!"); // construct a JLabel add( label ); // add the label to the JFrame
63
Containers hold Component References
MyFrame is a Container, because it inherits from JFrame, so GUI components can be added to it. class MyFrame extends Jframe{ } When a component is added to a container, a reference to the component is added to the list of components in the container.
64
Containers hold Component References
Graphically, the components added to a container appear within the rectangle on the monitor allocated to the container. In the example program, the JLabel is added to the frame MyFrame, and so appears within that area.
65
Picture of MyFrame MyFrame object is constructed using the class definition. The variable frame refers to this object.
66
Picture of MyFrame As the MyFrame object is constructed, a JLabel is constructed and added to the frame.
67
Picture of MyFrame After everything has been constructed and linked together with references, the graphics sytem takes over and draws visual version of all the components.
68
Example2: Program with a Button
import java.awt.*; import javax.swing.*; class ButtonFrame extends JFrame{ JButton bChange ; ButtonFrame(String title) { super( title ); //use super class constructor for Title setLayout( new FlowLayout() ); //layout manager bChange = new JButton("Click Me!"); //Create add( bChange ); //add it to the JFrame setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } new JButton("Click Me!") constructs a button object and puts the words "Click Me!" on it. The add() method of the frame puts the JButton into the frame
69
Example2: Program with a Button
A class with main method public class ButtonDemo{ public static void main ( String[] args ) { ButtonFrame frm = new ButtonFrame("Button Demo"); frm.setSize( 150, 75 ); frm.setVisible( true ); } }
70
Running the Program It gives:
…It looks nice, but nothing happens on clicking this button! …we need an action listener and the event handler codes
71
Buttons and Actions Adding a button to a frame Layout managers
This section discusses how to add a JButton to a frame and how to register a listener for its events. Adding a button to a frame Layout managers Action listeners Registering a listener with a GUI component The actionPerformed() method The content pane of a frame Changing the background color of a frame(optional)
72
Swing Components The picture shows how the class JButton fits into the Swing hierarchy Recall that many Swing classes start with J. Similar AWT classes do not start with J. A frequent error is to forget the J and get the wrong class.
73
Event Listener Object When a GUI program is running, the user generates an event by interacting with a GUI component. Here are some ways to generate an event: Moving the mouse Clicking on a button Typing some text into a text area
74
Event Listener Object For a program to respond to an event there must be an event listener object for it. A event listener object contains a listener method for a specific type of event. Programs ignore events if there is no listener for them.
75
Event Object An event listener is an object that "listens" for events from a GUI component, like a button. An event, like a button click, is represented as an object. When an event is generated, the system creates an event object which is then sent to the listener that has been registered for the GUI component. Then, a method in the listener object is invoked.
76
Event Object In the picture, the component is the button.
The user event is a click on that button. An Event object is sent to the registered listener. It is the responsibility of the listener to do something in response to the event
77
Event Object To be able to respond to events, a program must:
Create an event listener object for the type of event. Register the listener object with the GUI component that generates the event (or with a component that contains it).
78
bChange.addActionLister(handler)
Event Object To be able to respond to events, a program must: Create Register bChange Jbutton Object eventHandler Object bChange.addActionLister(handler)
79
ActionListener public void actionPerformed( ActionEvent evt){ } ;
A button listener must implement the ActionListener interface ActionListener is an interface (not a class) and has only one method called actionPerformed(). private class the handler implements ActionListener{ } public void actionPerformed( ActionEvent evt){ } ;
80
ActionListener A class that implements the interface must contain an actionPerformed() method. The ActionEvent parameter is an Event object that represents an event (a button click). It contains information about the event. private class thehandler implements ActionListener { public void actionPerformed( ActionEvent evt) //codes come here }
81
ActionListener About the ActionEvent class:
The entire point of event is to inform a listener that something has happened to a component in the GUI. An event includes all of the information that a listener needs to figure out what happened and to whom it happened (the what and who of the event). An event must give enough information to fully describe itself. That way, a listener can figure out what exactly happened and respond in a meaningful way.
82
ActionListener About the ActionEvent class:
Some methods of ActionEvent class: getSource() The getSource() method returns the object that generates the event (the who). getActionCommand The getActionCommand() method returns the command string that indicates the event's intended action, such as print or copy (the what).
83
Event handler class A class that implements the interface must contain an actionPerformed() method. private class thehandler implements ActionListener { public void actionPerformed( ActionEvent evt) String string=“”; If(event.getSource()==label1){ string = String.format(“Label1: %s”, event.getActionCommand()) } else //Add more } }
84
Registering the Listener
We have implemented the ActionLister, it is time to register: To register a listener to label1: first create an instance of the listener thehandler handler =new thehandler(); Then: register by using addActionListener() method label1.addActionListener(handler); textfield1.addActionListener(handler);
85
Code example //import Java.awt.FlowLayout
Java.awt.event.ActionListener Java.awt.event.ActionEvent Javax.swing.Jframe Javax.swing.JTextField Javax.swing.JOptionPane //import Java.awt.*; Javax.swing.*
86
Code example class MyFrame extends Jframe { JTextField item1;
JLabel labe1; public MyFrame(){ //codes for constructor } private class the handler implements ActionListener{ public void actionPerformed(ActionEvent event){ //codes for event here
87
Code example //codes for constructor public MyFrame(){ Super(“Title”);
setLayout(new FlowLayout()); item1=new JTextField(10); add(item1) thehandler handler=new thehandler(); item1.addActionLister(handler); }
88
Code example //codes for event
public void actionPerformed(ActionEvent event){ String string=“”; if (event.getSource()==item1) string=String.format(“item1: %s”, event.getActionCommand()); else //do something here for other events JOptionPane.ShowMessageDialog(null, string); }
89
Code example //main method public class MyFrameDemo{
Public static void main(String[] args){ MyFrame frame1= new MyFrame(); frame1.setSize( 400, 200 ); frame1.setVisible(true); Frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }
90
Complete example Complete sample codes for the following outputs are MyFrame.java and MyFrameDemo.java found in Sample codes folder
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.