Unit 3 Event and GUI Programming (NEP)
Unit 3 Event and GUI Programming (NEP)
Unit 3 Event and GUI Programming (NEP)
Unit-3
Event and GUI programing
Classification of Events
• Foreground Events
• Background Events
Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are generated
due to interaction by the user on components in Graphic User Interface (GUI). Interactions are nothing but
clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of these
events are operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur. To handle the
events, Java follows the Delegation Event model.
• Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed ( )
event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased ( )
handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped ( ) handler is invoked. A user interacts with the application by pressing either keys on the
keyboard or by using mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called ‘events’. Knowing these events will
enable the programmer to write his code according to the key pressed or mouse event.
source component.
3. int getY(); this method returns the vertical y postion of the event relative to the
source component.
Program to create a text area and display the mouse event when the button on the
mouse is clicked, when mouse is moved, etc. is done by user.
Handling Mouse Events
To handle mouse events, we must implement the MouseListener and the MouseMotion Listener
interfaces.
EX: // Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX = 0; // save coordinates
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX= 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg= "Up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
What is Panel
Panel is a component that allows placing multiple components on it. It is created using the Panel class. This class
inherits the Container class. Refer the below program.
In the above program, f is a Frame object while the panel is a Panel object. The panel object is placed according
to the specified location using setBounds method. The color of the panel is Gray. The b1 is a button object that is
placed according to the specified location. The color of the button is blue. Then, b1 button is added to the panel
and the panel is added to the Frame f1. Finally, the frame f1 is visible with the components.
What is Frame
Frame is a component that works as the main top-level window of the GUI application. It is created using the Frame
class. For any GUI application, the first step is to create a frame. There are two methods to create a frame: by
extending the Frame class or by creating an object of Frame class.
According to the above program (Figure 1), f is a Frame object. Other GUI components are added to it. Finally, the
frame is displayed. The frame is a resizable and a movable window. It has the title bar. The default visibility of a
Frame is hidden. The programmer has to make it visible by using setVisible method and providing the value “true”
to it.
Applets are small java programs that are primarily used in internet computing. It can be transported over the
internet from one computer to another and run using the Applet Viewer or any web browser that supports Java.
An applet is like an application program, it can do many things for us. It can perform arithmetic operations,
display graphics, create animation & games, play sounds and accept user input, etc. Every Java applet inherits
a set of default behaviours from the Applet class. As a result, when an applet is loaded, it undergoes a series of
changes in its states. Applet Life Cycle is defined as how the applet created, started, stopped and destroyed
during the entire execution of the application. The methods to execute in the Applet Life Cycle
are init(), start(), stop(), destroy(). The Applet Life Cycle Diagram is given as below:
o init(): The init() method is the first method to run that initializes the applet. It can be invoked only once at
the time of initialization. The web browser creates the initialized objects, i.e., the web browser (after
checking the security settings) runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet. It is invoked
immediately after the init() method is invoked. Every time the browser is loaded or refreshed, the start()
method is invoked. It is also invoked whenever the applet is maximized, restored, or moving from one tab
to another in the browser. It is in an inactive state until the init() method is invoked.
}
4. Idle State: An applet becomes idle when it is stopped from running. Stopping occurs automatically when we
leave the page containing the currently running applet. This is achieved by calling the stop() method explicitly.
o stop(): The stop() method stops the execution of the applet. The stop () method is invoked whenever the
applet is stopped, minimized, or moving from one tab to another in the browser, the stop() method is
invoked. When we go back to that page, the start() method is invoked again.
4.Display state:
5. Dead State: An applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy() method when we want to quit the browser.
public void destroy()
{
.............
.............
(Action)
o destroy(): The destroy() method destroys the applet after its work is done. It is invoked when the applet
window is closed or when the tab containing the webpage is closed. It removes the applet object from
memory and is executed only once. We cannot start the applet once it is destroyed.
Layout Manager
gridLayoutPanel1.add(gridLayoutPanel3);
add(flowLayoutPanel1, BorderLayout.NORTH);
add(flowLayoutPanel2, BorderLayout.SOUTH);
add(gridLayoutPanel1, BorderLayout.CENTER);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new LayoutManagerTest();
}
}
Output
Layout Managers
In Java, Layout Managers is used for arranging the components in order. LayoutMananger is an interface which
implements the classes of the layout manager.
Below are some of the class which are used for the representation of layout manager.
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
Border Layout
BorderLayout is used, when we want to arrange the components in five regions. The five regions can be north,
south, east, west and the centre. There are 5 types of constructor in Border Layout. They are as following:
Example:
import java.awt.*;
import javax.swing.*;
JFrame frame;
BorderDemo1()
frame=new JFrame();
frame.add(box1,BorderLayout.NORTH);
frame.add(box2,BorderLayout.SOUTH);
frame.add(box3,BorderLayout.EAST);
frame.add(box4,BorderLayout.WEST);
frame.add(box5,BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
new BorderDemo1();
Grid Layout
Grid Layout is used, when we want to arrange the components in a rectangular grid.
1. GridLayout()
Example:
import java.awt.*;
import javax.swing.*;
JFrame frame1;
GridDemo1(){
frame1=new JFrame();
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.setLayout(new GridLayout(3,3));
frame1.setSize(500,500);
frame1.setVisible(true);
new GridDemo1();
Flow Layout
Flow Layout is used, when we want to arrange the components in a sequence one after another.
There are 3 types of constructor in the Flow Layout. They are as following:
1. FlowLayout()
2. FlowLayout(int align)
Example:
import java.awt.*;
import javax.swing.*;
JFrame frame1;
FlowDemo1(){
frame1=new JFrame();
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.add(box10);
frame1.setLayout(new FlowLayout(FlowLayout.LEFT));
frame1.setSize(400,400);
frame1.setVisible(true);
new FlowDemo1();
Java’s GUI components include labels, text fields, text areas, buttons, pop-up menus, etc. The SWING Toolkit
also includes containers which can include these components. Containers include frames (windows), canvases
(which are used to draw on), and panels (which are used to group components). Panels, buttons, and other
components can be placed either directly in frames or in panels inside the frames.
These GUI components are automatically drawn whenever the window they are in is drawn. Thus we will not
need to explicitly put in commands to draw them..
Actions on these GUI components are handled using Java’s event model. When a user interacts with a
component (clicks on a button, types in a field, chooses from a pop-up menu, etc.), an event is generated by the
component that you interact with. For each component of your program, the programmer is required to designate
one or more objects to “listen” for events from that component. Thus if your program has a button labeled “start”
you must assign one or more objects that will be notified when a user clicks on the button.
1 Buttons:
JButton is a class in package javax.swing that represents buttons on the screen. The most common constructor is:
public JButton(String label);
which, when executed, creates a button with “label” printed on it. Generally the button is large enough to display
label. There is also a parameter less constructor that creates an unlabeled button. Buttons respond to a variety of
messages, but the only one likely to be useful to you is getText(), which returns a String representing the label on
the button.
You add an “ActionListener” to a button with the method:
public void addActionListener(ActionListener listener);
Labels
A JLabel is a very simple component which contains a string. The constructors are
public JLabel() // creates label with no text
public JLabel(String text) //create label with text
The methods available are
public String getText() // return label text
public void setText(String s) // sets the label text
Text Fields
A JTextField is an area that the user can type one line of text into. It is a good way of getting text
input from the user. The constructors are
public JTextField () // creates text field with no text
public JTextField (int columns)
// create text field with appropriate # of columns
public JTextField (String s) // create text field with s displayed
public JTextField (String s, int columns)
// create text field with s displayed & approp. width
Methods include:
public void setEditable(boolean s)
// if false the TextField is not user editable
public String getText() // return label text
Text Areas
JTextArea is a class that provides an area to hold multiple lines of text. It is fairly similar to JTextField
except that no special event is generated by hitting the return key.
The constructors are:
public JTextArea(int rows, int columns)
// create text field with appropriate # rows & columns
public JTextArea(String s, int rows, int columns)
// create text field with rows, columns, & displaying s
Methods:
public void setEditable(boolean s)
// if false the text area is not user editable
public String getText() // return text in the text area
public void setText(String s) // sets the text
public void append(String s) // append the text to text in the text area
JComboBox menus
JComboBox provides a pop-up list of items from which the user can make a selection.
The constructor is:
public JComboBox() // create new choice button
The most useful methods are:
public void addItem(Object s) // add s to list of choices
public int getItemCount() // return # choices in list
public Object getItemAt(int index) // return item at index
public Object getSelectedItem() // return selected item
public int getSelectedIndex() // return index of selected
When an object is added to a JComboBox, the results of sending toString() to the combo box is
displayed in the corrresponding menu.
You can also set the combo box so the user can type an element in the combo box rather than
being forced to select an item from the list. This is done by sending the combo box the message
setEditable(true).
When a user selects an item it generates an ActionEvent which can be handled as usual with an
actionPerformed method. One can determine whether the combo box generated the event by sending the event the
getSource() method, just as we did with other components
Check Boxes
The JCheckbox class provides support for check box buttons. You can also put check boxes in menus, using
the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem inherit from AbstractButton
Check boxes are similar to radio buttons but their selection model is different, by convention. Any number of
check boxes in a group — none, some, or all — can be selected. A group of radio buttons, on the other hand, can
have only one button selected.
chinButton.setMnemonic (KeyEvent.VK_C);
chinButton.setSelected (true);
Radio buttons
Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected. The Swing
release supports radio buttons with the JRadioButton and ButtonGroup classes. To put a radio button in
a menu, use the JRadioButtonMenuItem class. Other ways of displaying one-of-many choices are combo
boxes and lists. Radio buttons look similar to check boxes, but, by convention, check boxes place no limits on how
many items can be selected at a time.
Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual button
characteristics
Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows
us to see invisible number of rows and columns .It can be added to top-level container like Frame or a component
like Panel. The Scrollbar class extends the Component class.
Menus
A menu is a list of buttons each of which have their own corresponding action when selected. Types of menus
include:
DIALOG BOX
A dialog box is: • a separate window that pops up in response to an event occurring in a window. often used to
obtain information from the user (e.g., entering some values such as when filling out a form).
4. Option Dialog - asks the user to select some option JAVA has a class called JOptionP
Sliders
The Java JSlider class is used to create the slider. By using JSlider, a user can set value from a specific range.
type of output irrespective of the underlying platform. AWT on the other hand, is more dependent on the
underlying operating system for generating the graphic components; thus the output may vary from one
platform to another.
Swings can be regarded as more graphically-rich than AWT not only because they provide some entirely
new graphical components (like tabbed window and tree structure) but also due to the fact that they have
enhanced some of the conventional AWT components (like buttons with both image and text).
I/O programming
Files
Java provides many classes for performing text I/O and binary I/O
Text I/O
• Use the Scanner class for reading text data from a file
• The JVM converts a file specific encoding when to Unicode when reading a character
Binary I/O
• Binary I/O does not involve encoding or decoding and thus is more efficient than text I/O
• Binary files are independent of the encoding scheme on the host machine
• The abstract InputStream is the root class for reading binary data
• The abstract OutputStream is the root class for writing binary data
• A java.io. FileNotFoundException will occur if you attempt to create a FileInputStream with a nonexistent file
• If the file already exists, the first two constructors will delete the current contents in the file
• To retain the current content and append new data into the file, use the last two constructors by passing true to
• All the methods in FileInputStream and FileOutputStream are inherited from their superclasses
try
output.write(i);
try
int value;
The super class InputStream is an abstract class, and therefore we cannot create
instances of this class. Rather, we must use the subclasses that inherit from this class.
The InputStream class defines methods for performing input functions such as
• Reading bytes
• Closing streams
Method Description
read ( ) Reads a byte from the input stream
Reads an array of bytes into b
read ( byte b [ ] )
read ( byte b [ ], int n, int m ) Reads m bytes into b starting from nth byte
Note that the class DataInputStream extends FilterInputStream and implements the interface
DataInput. Therefore, the DataInputStream class implements the methods described in DataInput
in addition to using the methods of InputStream class. The DataInput interface contains the
following methods:
* readShort ( ) * readFloat ( )
* reading ( ) * readUTF ( )
* readLong ( ) * readDouble ( )
* readLine ( ) * readChar ( )
* readBoolean ( )
Output stream classes are derived from the base class OutputStream. Like InputStream,
the OutputStream is an abstract class and therefore we cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.
The OutputStream includes methods that are designed to perform the following tasks.
• Writing bytes
• Closing streams
• Flushing streams
Method Description
write ( byte b[ ], int, int m ) Writes m bytes from array b starting from nth byte
The ObjectInputStream class of the java.io package can be used to read objects that were
Working of ObjectInputStream
Create an ObjectInputStream
ObjectOutputStream
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can
be accomplished by using a file for the stream.
• Only objects that support the java.io.Serializable interface can be written to streams. The
class of each serializable object is encoded including the class name and signature of the
class, the values of the object’s fields and arrays, and the closure of any other objects
referenced from the initial objects.
• The Java ObjectOutputStream is often used together with a Java ObjectInputStream. The
ObjectOutputStream is used to write the Java objects, and the ObjectInputStream is used to
read the objects again.
Methods
• void close() : Closes the stream.This method must be called to release any resources
associated with the stream.
This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor
we do the read write operations. If end-of-file is reached before the desired number of byte has been
read than EOFException is thrown. It is a type of IOException.
Declaration :
1.read() : java.io.RandomAccessFile.read() reads byte of data from file. The byte is returned as an
integer in the range 0-255
Syntax :
public int read(byte[] b)
SHWETHA RANI R S 1ST BCA Page 34
OBJECT ORIENTED PROGRAMMING WITH JAVA
Syntax :
public final char readChar()