0% found this document useful (0 votes)
7 views32 pages

JAVA using oops

This document covers Event and GUI programming in Java, focusing on the Abstract Window Toolkit (AWT) for creating graphical user interfaces. It details various components like frames, buttons, labels, text fields, and event handling mechanisms, including examples of how to implement these elements in Java code. Additionally, it introduces applets, their lifecycle, and event delegation models, along with practical examples for better understanding.

Uploaded by

Mgm Mallikarjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views32 pages

JAVA using oops

This document covers Event and GUI programming in Java, focusing on the Abstract Window Toolkit (AWT) for creating graphical user interfaces. It details various components like frames, buttons, labels, text fields, and event handling mechanisms, including examples of how to implement these elements in Java code. Additionally, it introduces applets, their lifecycle, and event delegation models, along with practical examples for better understanding.

Uploaded by

Mgm Mallikarjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Unit – 4- Event and GUI programming:

Event and GUI programming: Event handling in java, Event types, Mouse and key
events, GUI Basics, Panels, Frames, Layout Managers: Flow Layout, Border Layout,
Grid Layout, GUI components like Buttons, Check Boxes, Radio Buttons, Labels,
Text Fields, Text Areas, Combo Boxes, Lists, Scroll Bars, Sliders, Windows, Menus,
Dialog Box, Applet and its life cycle, Introduction to swing, Exceptional handling
mechanism.

GUI Basics
 AWT stands for Abstract window toolkit is an Application programming interface
(API) for creating Graphical User Interface (GUI) in Java.
 Java AWT contains large number of classes and methods to create and manage
graphical user interface ( GUI )

Containers in java
A Container is a subclass of Component that can contain other components.
There are four types of containers available in AWT:
 Window,
 Frame,
 Dialog
 Panel.

Page 1
Window: An instance of the Window class has no border and no title
Dialog: Dialog class has border and title.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for
holding components.
Frame: A frame has title, border and menu bars. It can contain several components like
buttons, text fields, scrollbars etc. This is most widely used container while developing
an application in AWT.
We can create a GUI using Frame in two ways:
1) By creating the instance of Frame class
2) By extending Frame class
1. By Creating an Instance of Frame class
Here, we directly create a Frame object inside main().
import java.awt.*;
public class FrameExample1
{
public static void main(String[] args)
{
Frame f = new Frame("AWT Frame Example");
f.setSize(300, 200);
f.setVisible(true);
}
}
Explanation:
import java.awt.*; : imports all the classes from the AWT package which is used for GUI
components like Frame, Button, Label, etc.
public class FrameExample1 { : declares a public class named FrameExample1.
public static void main(String[] args) { : main method where the program execution starts.
Frame f = new Frame("AWT Frame Example"); : creates a Frame object named f with the title
“AWT Frame Example”.
f.setSize(300, 200); : sets the window width to 300 pixels and height to 200 pixels.
f.setVisible(true); : makes the Frame visible on the screen (it is hidden by default).

2. By Extending the Frame class


Here, we make our own class a subclass of Frame.
import java.awt.*;
public class FrameExample2 extends Frame
{
FrameExample2()
{
setTitle("AWT Frame using Inheritance");
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args)


{
new FrameExample2();
}
}
 Explanation:
import java.awt.*; : imports the AWT package for GUI components.
public class FrameExample2 extends Frame { : defines a class that inherits from Frame, so
it directly becomes a window.
FrameExample2() : constructor of the class that runs automatically when an object is created.
setTitle("AWT Frame using Inheritance"); : sets the title of the Frame window.
setSize(300, 200); : sets the window dimensions to 300×200 pixels.
setVisible(true); : displays the Frame on the screen.
public static void main(String[] args) { : starting point of the program.
new FrameExample2(); : creates an object of the class which automatically displays the window.

Constructing a Component and Adding it into a Container in Java AWT 👇


Steps:
1. Create a Frame (Container).
2. Create a Component (like Label, Button, or TextField).
3. Add the Component to the Frame using add() method.
4. Set size, layout, and visibility of the Frame.

Button Class Constructors


AWT Button
In Java, AWT contains a Button Class. It is used for creating a labeled button which can
perform an action.

Simple Example:
import java.awt.*;
public class AddComponentExample
{
public static void main(String[] args)
{
Frame f = new Frame("Add Component Example"); // Step 1: Create container
Button b = new Button("Click Me"); // Step 2: Create component
f.add(b); // Step 3: Add component 2 container
f.setSize(300, 200); // Step 4: Set size(w,h)
f.setVisible(true); // Step 5: Make visible
}
}
Explanation:
 Frame → acts as the container.
 Button → is the component.
 add(b) → adds the button to the frame.
 setVisible(true) → displays the frame on screen.

AWT Label
A Label in Java AWT is a component used to display a single line of text that the user cannot edit.
It’s often used to identify other GUI components like text fields or buttons.

Example:

import java.awt.*;

public class LabelExample {


public static void main(String[] args) {
Frame f = new Frame("AWT Label Example");

Label l1 = new Label("Hello, this is Label 1");


Label l2 = new Label("This is Label 2");

f.add(l1);
f.add(l2);

f.setSize(300, 150);
f.setVisible(true);
}
}
Explanation:
import java.awt.*; : imports AWT classes for GUI.
Frame f = new Frame("AWT Label Example"); : creates a window.
Label l1/l2 : creates labels with text.
f.add(l1/l2); : adds labels to the window.
f.setSize(300, 150); : sets the window size.
f.setVisible(true); : shows the window.

Example program
import java.awt.*; class LabelDemo1
{
public static void main(String args[])
{
Frame f= new Frame(" Label Demo");
Label l1 =new Label("Welcome ");
l1.setBounds(50,50,200,30);
Label l2=new Label("This Tutorial is of Java");
ab2.setBounds(50,100,200,30);
f.add(l1);
f.add(l2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}
AWT TextField:
 A TextField is a GUI component that allows the user to enter or edit a single line of text.
 It is often used to take input from the user.

Constructors:
 TextField() → creates an empty text field.
 TextField(String text) → creates a text field with initial text.
 TextField(int columns) → creates a text field with specified width in columns.
 TextField(String text, int columns) → creates text field with text and width.

Common Methods:
 setText(String text) → sets the text.
 getText() → retrieves the text.
 setEditable(boolean b) → allows or prevents editing.

Simple Example:
import java.awt.*;
public class TextFieldExample
{
public static void main(String[] args)
{
Frame f = new Frame("AWT TextField Example");
TextField tf1 = new TextField(); // empty text field
TextField tf2 = new TextField("Hello TextField"); // with initial text
f.add(tf1);
f.add(tf2);
f.setSize(300, 150);
f.setVisible(true);
}
}
Explanation:
 TextField tf1 → empty field where user can type.
 TextField tf2 → field with default text.
 f.add(tf1/tf2) → adds text fields to the frame.
 FlowLayout arranges them in a row.
 setVisible(true) → displays the frame.
import java.awt.*;
class TextFieldDemo1
{
public static void main(String args[])
{
Frame f= new Frame("TextField Demo");
TextField t1,t2;
t1=new TextField("Welcome ");
t1.setBounds(60,100, 230,40);
t2=new TextField("This tutorial is of Java");
t2.setBounds(60,150, 230,40);
f.add(text1);
f.add(text2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}

AWT TextArea

In Java, AWT contains aTextArea Class. It is used for displaying multiple-line text.
Narasimha Murthy G K Page 7
Example Program

import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame f= new Frame();
TextArea area=new TextArea("Welcome ");
area.setBounds(30,40, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}

AWT Checkbox

In Java, AWT contains a Checkbox Class. It is used when we want to select only one
option i.e true or false. When the checkbox is checked then its state is "on" (true) else it
is "off"(false).

Page 8
Example program

import java.awt.*;

public class CheckboxDemo1

CheckboxDemo1(){

Frame f= new Frame("Checkbox Example");

Checkbox ckbox1 = new Checkbox("Yes", true);

ckbox1.setBounds(100,100, 60,60);

Checkbox ckbox2 = new Checkbox("No");

ckbox2.setBounds(100,150, 60,60);

f.add(ckbox1);

f.add(ckbox2);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[])

new CheckboxDemo1();

Page 9
AWT List

List class is used to create a list with multiple values, allowing a user to select any of
the values. When a value is selected from List, an ItemEvent is generated, which is
handled by implementing ItemListener interface.

Constructors of List

Example Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ListEx1


{
String [] seasons;
Frame jf;
List list;
Label label1;

ListEx1()
{
jf= new Frame("List");
list= new List(7);
label1 = new Label("Select your favorite sports from the list :");

list.add("Badminton");
list.add("Hockey");
list.add("Tennis");
list.add("Football");
list.add("Cricket");
list.add("Formula One");
list.add("Rugby");

Page 10
jf.add(label1);
jf.add(list);

jf.setLayout(new FlowLayout());
jf.setSize(260,220);
jf.setVisible(true);
}

public static void main(String... ar)


{
new ListEx1();
}

Output

Menu bar
 A menu bar can be created using MenuBar class.
 A menu bar may contain one or multiple menus, and these menus are created
using Menu class.
 A menu may contain one of multiple menu items and these menu items are created
using MenuItem class.

Page 11
Simple constructors of MenuBar, Menu and MenuItem

Example Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MenuEx1


{
Frame frame;
MenuBar menuBar;
Menu menu1, menu2;
MenuItem mItem1, mItem2, mItem3, mItem4, mItem5, mItem6,
mItem7;
Button button1, button2, button3;
Dialog d1, d2, d3;

MenuEx1()
{
frame = new Frame("MenuBar, Menu and MenuItems");

//Creating a menu bar


menuBar= new MenuBar();

//Creating first menu


menu1 = new Menu("File");
mItem1 = new MenuItem("New");
mItem2 = new MenuItem("Open");
mItem3 = new MenuItem("Save");

//Adding menu items to the menu


menu1.add(mItem1);

Page 12
menu1.add(mItem2);
menu1.add(mItem3);

//Creating a second sub-menu


menu2 = new Menu("Save-as");
mItem5 = new MenuItem(".jpeg");
mItem6 = new MenuItem(".png");
mItem7 = new MenuItem(".pdf");

//Adding menu items to the sub-menu


menu2.add(mItem5);
menu2.add(mItem6);
menu2.add(mItem7);

//Adding the sub-menu to the first menu


menu1.add(menu2);

//Adding our menu to the menu bar


menuBar.add(menu1);

//Adding my menu bar to the frame by calling setMenuBar()


method
frame.setMenuBar(menuBar);

frame.setSize(330,250);
frame.setVisible(true);
}

public static void main(String... ar)


{
new MenuEx1();
}
}
OutPut

Page 13
Applet

 An applet is a Java program that can be embedded inside a web page to


generate the dynamic content.
 It runs inside the browser and works at client side.

Life cycle of an applet

Page 14
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It
is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

Benefits of java Applet

 They are very secure.


 It works at client side so less response time.
 Applets can be executed by browsers running under different platforms.

HelloWorld.java

Now you have to create an HTML File that Includes the Applet.
Using a text editor, create a file named Hello.html in the same directory that
contains HelloWorld.class.

Page 15
Simple example of Applet by appletviewer

Page 16
Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.

Page 17
Example

GraphicsDemo.java

Page 18
Displaying Image in Applet

The java.awt.Graphics class provide a method drawImage() to display the image.

Syntax
1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.

Other required methods of Applet class to display image:

 getCodeBase() Gets the base URL.

 getDocumentBase() Gets the URL of the document in which the applet is


embedded.

Page 19
Example of displaying image in applet

Myappelt.html

Page 20
Event Handling
Event handling has three main components,
 Events : An event is a change of state of an object.
 Events Source : Event source is an object that generates an event.(producer of an
event)
 Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs. Listener is responsible for generating response to an event.

In event Delegation model


 Event Listeners Register with the source.
 Source Generates the event, makes an event object and send it to the listeners.
 Listeners Process the event object and returns

Important Event Class and Listeners Interface are

Page 21
ActionEvent and ActionListener

An event of type ActionEvent class is generated when a source such as -


 A button is clicked, or,
 An item in the list is double-clicked, or,
 A menu item is selected in the menu.

The class which processes ActionEvent should implement ActionListener Interface

ActionListner Interface provides method

Example Program

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class AnAppletWithButtons extends Applet implements ActionListener {

Page 22
Button button1, button2;

public void init() {


button1 = new Button("Button 1");
add(button1);
button1.addActionListener(this);

button2 = new Button("Button 2");


add(button2);
button2.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == button1)
System.out.println("Button 1 was pressed");
else
System.out.println("Button 2 was pressed");
}

MouseEvent and MouseListener

An event of type MouseEvent is generated in a situations when -


 A mouse cursor enters a window area.
 A mouse cursor exists a window area.
 A mouse button is being pressed.
 A mouse button is released.

The class which processes MouseEvent t should implement MouseListener


Interface

MouseListener Interface provides the following method

Page 23
KeyEvent and KeyListener

An event of type KeyEvent class is generated when a source such as, a key on the
keyboard is pressed in a textfield or in a textarea.

Some methods of KeyEvent class

Page 24
The class which processs the keyEvent should implement Key Listener Interface
The method of the keyListner Interface are

Layout Managers

In Java, Layout Managers is an object that determines the way that Components are
arranged in a container

There are several predefined layout manager They are

1. java.awt.BorderLayout

2. java.awt.FlowLayout

3. java.awt.GridLayout

4. java.awt.CardLayout

5. javax.swing.BoxLayou

Page 25
java.awt.FlowLayout

The flow layout manager arranges the components one after another from left-to-right
and top-to-bottom manner. The flow layout manager gives some space between
components.
There are 3 types of constructor in the Flow Layout. They are as following:
1. FlowLayout()
2. FlowLayout(int align)
3. FlowLayout(int align, int hgap, int vgap)

The constant align in FlowLayout, may take one of these values

import java.awt.*;
import javax.swing.*;

public class FlowDemo1{


JFrame frame1;
FlowDemo1() {
frame1=new JFrame();

JButton box1=new JButton("1");


JButton box2=new JButton("2");
JButton box3=new JButton("3");
JButton box4=new JButton("4");
JButton box5=new JButton("5");
JButton box6=new JButton("6");
JButton box7=new JButton("7");
JButton box8=new JButton("8");
JButton box9=new JButton("9");

Page 26
JButton box10=new JButton("10");

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);
}
public static void main(String[] args)
{
new FlowDemo1();
}
}
Output

BorderLayout

BorderLayout arranges the components in the five regions. Four sides are referred to
as north, south, east, and west. The middle part is called the center. Each region can

Page 27
contain only one component and is identified by a corresponding constant
as NORTH, SOUTH, EAST, WEST, and CENTER.

Constructors:

 BorderLayout(): It will construct a new borderlayout with no gaps between the


components.
 BorderLayout(int, int): It will constructs a border layout with the specified
gaps between the components.

//Java Program illustrating the BorderLayout


import java.awt.*;
import javax.swing.*;
public class border
{
JFrame JF;
border()
{
JF=new JFrame(); //JFrame object
//Lying at top, will be the button named 'North'
JButton b1=new JButton("NORTH");
//Lying at bottom, will be the button named 'South'
JButton b2=new JButton("SOUTH");
//Lying at left, will be the button named 'East'
JButton b3=new JButton("EAST");
//Lying at right, will be the button named 'West'
JButton b4=new JButton("WEST");
//In the center, will be the button named 'Center'
JButton b5=new JButton("CENTER");
//Adding our buttons
JF.add(b1,BorderLayout.NORTH);
JF.add(b2,BorderLayout.SOUTH);
JF.add(b3,BorderLayout.EAST);
JF.add(b4,BorderLayout.WEST);
JF.add(b5,BorderLayout.CENTER);
//Function to set size of the Frame
JF.setSize(300, 300);
//Function to set visible status of the frame
JF.setVisible(true);
}
Page 28
//Driver Code
public static void main(String[] args)
{
//Calling the constructor
new border();
}
}

OutPut

Grid Layout

Grid Layout is used, when we want to arrange the components in a rectangular grid.

Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns along with given horizontal and vertical gaps.

Example Program

import java.awt.*;
import javax.swing.*;

public class GridDemo1{

Page 29
JFrame frame1;
GridDemo1(){
frame1=new JFrame();

JButton box1=new JButton("*1*");


JButton box2=new JButton("*2*");
JButton box3=new JButton("*3*");
JButton box4=new JButton("*4*");
JButton box5=new JButton("*5*");
JButton box6=new JButton("*6*");
JButton box7=new JButton("*7*");
JButton box8=new JButton("*8*");
JButton box9=new JButton("*9*");

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);
}
public static void main(String[] args) {
new GridDemo1();
}
}

output

Page 30
JavaSwing

Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

Page 31
Page 32

You might also like