Chapter 08 - GUI Programming

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

Object Oriented Programming

19CSE (2nd Semester)


Chapter#08: GUI Programming

1
Java GUI Event Handling 2

What is an Event?
 Change in the state of an object is known as event i.e. event describes the
change in state of source.
 Events are generated as result of user interaction with the graphical user
interface components.
 For example, clicking on a button, moving the mouse, entering a character
through key-board, selecting an item from list, scrolling the page are the
activities that causes an event to happen.
 Any program that uses GUI (graphical user interface) such as Java
application written for windows, is event driven.

How events are handled?


 A source generates an Event and send it to one or more listeners registered
with the source.
 Once event is received by the listener, they process the event and then
return.
 Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.
 2002 Prentice Hall. All rights reserved.
Java GUI Event Handling 3

What is an Event Handling?


 Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
 This mechanism have the code which is known as event handler that is
executed when an event occurs.
 Java Uses the Delegation Event Model to handle the events.
 This model defines the standard mechanism to generate and handle the
events.
 Components of Event Handling
 Event handling has three main components,
 Events : An event is a change in state of an object.
 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets
notified when an event occurs.
 Steps to handle events:
 Implement appropriate interface in the class.
 Register the component with the listener.
 2002 Prentice Hall. All rights reserved.
Event-Handling Model

 Event-handling model
 Three parts
Event source
GUI component with which user interacts
Event object
Encapsulates information about event that occurred
Event listener
Receives event object when notified, then responds
 Programmer must perform two tasks
Register event listener for event source
Implement event-handling method (event handler)

 2002 Prentice Hall. All rights reserved.


Java GUI Event Handling 5

Event Classes Description Listener Interface


ActionEvent generated when button is pressed, menu-item is selected, ActionListener
list-item is double clicked
MouseEvent generated when mouse is dragged, moved, clicked, pressed MouseListener
or released and also when it enters or exit a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener


MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
WindowEvent generated when window is activated, deactivated, WindowListener
deiconified, iconified, opened or closed
ComponentEvent generated when component is hidden, moved, resized or set ComponentEventListene
visible r
ContainerEvent generated when component is added or removed from ContainerListener
container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
FocusEvent generated when component gains or loses keyboard focus FocusListener

 2002 Prentice Hall. All rights reserved.


Some basic GUI components.

Co m p o ne nt De sc rip tio n
JLabel An area where uneditable text or icons can be displayed.
JTextField An area in which the user inputs data from the keyboard.
The area can also display information.
JButton An area that triggers an event when clicked.
JCheckBox A GUI component that is either selected or not selected.
JComboBox A drop-down list of items from which the user can make
a selection by clicking an item in the list or possibly by
typing into the box.
JList An area where a list of items is displayed from which the
user can make a selection by clicking once on any
element in the list. Double-clicking an element in the list
generates an action event. Multiple elements can be
selected.
JPanel A container in which components can be placed.
So m e ba sic GUI c o m po ne nts.

 2002 Prentice Hall. All rights reserved.


Applet to Calculate factorial of a number 7

import java.awt.event.*;
import java.applet.*;
/*
<applet code="FactApplet" width=400 height=300>
</applet>
*/

public class FactApplet extends Applet implements ActionListener


{
TextField number,factorial; public void actionPerformed(ActionEvent e)
Button compute; {
public void init() String snumber;
{ snumber = number.getText();
Label numberp = new Label("Input Number: "); int inumber = Integer.parseInt(snumber);
Label factorialp = new Label("Factorial: "); factorial.setText(((Double)getFactorial(inumber)).toStr
number= new TextField(30); }
factorial = new TextField(30);
compute = new Button("Compute"); double getFactorial(int k)
add(numberp); {
add(number); double fact = 1;
add(factorialp); for(int i=1;i<=k;i++)
add(factorial); fact = fact * i;
add(compute); return fact;
compute.addActionListener(this); }
} }// end of class body

 2002 Prentice Hall. All rights reserved.


Java GUI Event Handling 8

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
 2002 Prentice Hall. All rights reserved.
Java Layout Manager 9

 The Layout manager is used to layout (or arrange) the GUI java
components inside a Container.
 There are many layout managers, but the most frequently used are-
Java BorderLayout
 A BorderLayout places components in up to five areas: top, bottom, left,
right, and center.
 It is the default layout manager for every java JFrame

Java FlowLayout
 FlowLayout is the default layout manager for every JPanel.
 It simply lays out components in a single row one after the other.

 2002 Prentice Hall. All rights reserved.


Java Layout Manager 10

Java GridBagLayout
 It is the more sophisticated of all layouts.
 It aligns components by placing them within a grid of cells, allowing
components to span more than one cell.

What is a container class?


 Container classes are classes that can have other components on it. So for
creating a GUI, we need at least one container object. There are 3 types of
containers.
 Panel: It is a pure container and is not a window in itself. The sole purpose
of a Panel is to organize the components on to a window.
 Frame: It is a fully functioning window with its title and icons.
 Dialog: It can be thought of like a pop-up window that pops out when a
message has to be displayed. It is not a fully functioning window like the
Frame.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 11

Step-01: Creating a Project


The first step is to create an IDE project for the application that we are going
to develop. Suppose we are creating GUI to perform addition between
numbers, so we will name our project NumberAddition.
 Choose File > New Project. Alternatively, you can click the New Project
icon in the IDE toolbar.
 In the Categories pane, select the Java node. In the Projects pane, choose
Java Application. Click Next.
 Type NumberAddition in the Project Name field and specify a path, for
example, in your home directory, as the project location.
 (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox
and specify the location for the libraries folder. See Sharing a Library with
Other Users in Developing Applications with NetBeans IDE for more
information.
 Deselect the Create Main Class checkbox if it is selected.
 Click Finish.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 12

Step-02: Building the Front End


 To proceed with building our interface, we need to create a Java container
within which we will place the other required GUI components.
 In this step we'll create a container using the JFrame component.
 We will place the container in a new package, which will appear within the
Source Packages node.
Create a JFrame container
1) In the Projects window, right-click the NumberAddition node and
choose New > Other.
2) In the New File dialog box, choose the Swing GUI Forms category and
the JFrame Form file type. Click Next.
3) Enter NumberAdditionUI as the class name.
4) Enter my.numberaddition as the package.
5) Click Finish.
 The IDE creates the NumberAdditionUI form and
the NumberAdditionUI class within the NumberAddition application, and
opens the NumberAdditionUI form in the GUI Builder.
 The my.NumberAddition package replaces the default package.
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 13

Adding Components: Making the Front End


 To proceed Adding Components: Making the Front End
 Next we will use the Palette to populate our application's front end with a
JPanel.
 Then we will add three JLabels, three JTextFields, and three JButtons.
 If you have not used the GUI Builder before, you might find information in
the Designing a Swing GUI in NetBeans IDE tutorial on positioning
components useful.
 Once you are done dragging and positioning the aforementioned components,
the JFrame should look something like the following screenshot.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 14

Adding Components: Making the Front End


 If you do not see the Palette window in the upper right corner of the IDE,
choose Window > Palette.
1) Start by selecting a Panel from the Swing Containers category on Palette and
drop it onto the JFrame.
2) While the JPanel is highlighted, go to the Properties window and click the
ellipsis (...) button next to Border to choose a border style.
3) In the Border dialog, select TitledBorder from the list, and type in Number
Addition in the Title field. Click OK to save the changes and exit the dialog.
4) You should now see an empty titled JFrame that says Number Addition like
in the screenshot. Look at the screenshot and add three JLabels, three
JTextFields and three JButtons as you see above.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 15

Renaming the Components


 In this step we are going to rename the display text of the components that
were just added to the JFrame.
1) Double-click jLabel1 and change the text property to First Number:.
2) Double-click jLabel2 and change the text to Second Number:.
3) Double-click jLabel3 and change the text to Result:.
4) Delete the sample text from jTextField1. You can make the display text
editable by right-clicking the text field and choosing Edit Text from the
popup menu. You may have to resize the jTextField1 to its original size.
Repeat this step for jTextField2 and jTextField3.
5) Rename the display text of jButton1 to Clear. (You can edit a button's text by
right-clicking the button and choosing Edit Text. Or you can click the button,
pause, and then click again.)
6) Rename the display text of jButton2 to Add.
7) Rename the display text of jButton3 to Exit.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 16

Step-03: Renaming the Components


 Your Finished GUI should now look like the following screenshot:

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 17

Step-03: Adding Functionality


 In this step we are going to give functionality to the Add, Clear, and Exit
buttons.
 The jTextField1 and jTextField2 boxes will be used for user input
and jTextField3 for program output - what we are creating is a very simple
calculator. Let's begin.
Making the Exit Button Work
 In order to give function to the buttons, we have to assign an event handler to
each to respond to events.
 In our case we want to know when the button is pressed, either by mouse
click or via keyboard. So we will use ActionListener responding to
ActionEvent.
1) Right click the Exit button. From the pop-up menu choose Events > Action >
actionPerformed. Note that the menu contains many more events you can
respond to! When you select the actionPerformed event, the IDE will
automatically add an ActionListener to the Exit button and generate a
handler method for handling the listener's actionPerformed method.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 18

Step-03: Adding Functionality.


Making the Exit Button Work
2) The IDE will open up the Source Code window and scroll to where you
implement the action you want the button to do when the button is pressed
(either by mouse click or via keyboard). Your Source Code window should
contain the following lines:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
//TODO add your handling code here:
}
3) We are now going to add code for what we want the Exit Button to do.
Replace the TODO line with System.exit(0);. Your finished Exit button code
should look like this:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 19

Step-03: Adding Functionality.


Making the Clear Button Work
1) Click the Design tab at the top of your work area to go back to the Form
Design.
2) Right click the Clear button (jButton1). From the pop-up menu select Events
> Action > actionPerformed.
3) We are going to have the Clear button erase all text from the jTextFields. To
do this, you will add some code like above. Your finished source code should
look like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
 The above code changes the text in all three of our JTextFields to nothing, in
essence it is overwriting the existing Text with a blank.
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 20

Step-03: Adding Functionality.


Making the ADD Button Work
 The Add button will perform three actions.
1) It is going to accept user input from jTextField1 and jTextField2 and convert
the input from a type String to a float.
2) It will then perform addition of the two numbers.
3) And finally, it will convert the sum to a type String and place it in
jTextField3.
 Lets get started!
1) Click the Design tab at the top of your work area to go back to the Form
Design.
2) Right-click the Add button (jButton2). From the pop-up menu, select Events
> Action > actionPerformed.
3) We are going to add some code to have our Add button work. The finished
source code shall look like this:

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 21

Step-03: Adding Functionality.


Making the ADD Button Work
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to change the value of result from a
//float to a string.
jTextField3.setText(String.valueOf(result));
}

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 22

Step-04: Running the Program


To run the program in the IDE:
 Choose Run > Run Project (Number Addition) (alternatively, press F6).
 Note: If you get a window informing you that Project NumberAddition does
not have a main class set, then you should
select my.NumberAddition.NumberAdditionUI as the main class in the same
window and click the OK button.
To run the program outside of the IDE:
1) Choose Run > Clean and Build Main Project (Shift-F11) to build the
application JAR file.
2) Using your system's file explorer or file manager, navigate to
the NumberAddition/dist directory.Note: The location of
the NumberAddition project directory depends on the path you specified
while creating the project in step 3 of the Step 1: Creating a Project
 section.
3) Double-click the NumberAddition.jar file.
 After a few seconds, the application should start.
 Note: If double-clicking the JAR file does not launch the application, see 
this article for information on setting JAR file associations in your operating
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 23

Step-04: Running the Program


 You can also launch the application from the command line.
To launch the application from the command line:
1) On your system, open up a command prompt or terminal window.
2) In the command prompt, change directories to
the NumberAddition/dist directory.
3) At the command line, type the following statement:
java -jar NumberAddition.jar
 Note: Make sure my.NumberAddition.NumberAdditionUI is set as the main
class before running the application.
 You can check this by right-clicking the NumberAddition project node in the
Projects pane, choosing Properties in the popup menu, and selecting the Run
category in the Project Properties dialog box.
 The Main Class field should display my.numberaddition.NumberAdditionUI.

 2002 Prentice Hall. All rights reserved.

You might also like