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

New Java

This document covers Event and GUI programming in Java, focusing on AWT (Abstract Window Toolkit) for creating graphical user interfaces. It details various components like Frames, Buttons, Labels, TextFields, and their usage, along with event handling and applet lifecycle. Additionally, it provides code examples demonstrating the creation and management of GUI components and menus.

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 views23 pages

New Java

This document covers Event and GUI programming in Java, focusing on AWT (Abstract Window Toolkit) for creating graphical user interfaces. It details various components like Frames, Buttons, Labels, TextFields, and their usage, along with event handling and applet lifecycle. Additionally, it provides code examples demonstrating the creation and management of GUI components and menus.

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

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 [Link].*;
public class FrameExample1
{
public static void main(String[] args)
{
Frame f = new Frame("AWT Frame Example");
[Link](300, 200);
[Link](true);
}
}
Explanation:
import [Link].*; : 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”.
[Link](300, 200); : sets the window width to 300 pixels and height to 200 pixels.
[Link](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 [Link].*;
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 [Link].*; : 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 [Link].*;
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
[Link](b); // Step 3: Add component 2 container
[Link](300, 200); // Step 4: Set size(w,h)
[Link](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 [Link].*;
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");
[Link](l1);
[Link](l2);
[Link](300, 150);
[Link](true);
}
}
Explanation:
import [Link].*; : imports AWT classes for GUI.
Frame f = new Frame("AWT Label Example"); : creates a window.
Label l1/l2 : creates labels with text.
[Link](l1/l2); : adds labels to the window.
[Link](300, 150); : sets the window size.
[Link](true); : shows the window.

Example program
import [Link].*; class LabelDemo1
{
public static void main(String args[])
{
Frame f= new Frame(" Label Demo");
Label l1 =new Label("Welcome ");
[Link](50,50,200,30);
Label l2=new Label("This Tutorial is of Java");
[Link](50,100,200,30);
[Link](l1);
[Link](l2);
[Link](500,500);
[Link](null);
[Link](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 [Link].*; // Import AWT package
public class TextFieldExample
{
public static void main(String[] args)
{
Frame f = new Frame("TextField Example"); // Create frame window

TextField t1 = new TextField(); // Empty text field


[Link](50, 50, 200, 30); // Set position and size
TextField t2 = new TextField("Hello"); // Text field with default text
[Link](50, 100, 200, 30); // Set position and size

[Link](t1); // Add first text field


[Link](t2); // Add second text field

[Link](300, 200); // Set frame size


[Link](null); // Use no layout manager
[Link](true); // Make frame visible
}
}
Explanation:
 TextField t1 → empty field where user can type.
 TextField t2 → field with default text.
 [Link](t1/t2) → adds text fields to the frame.
 setVisible(true) → displays the frame.
AWT TextArea

In Java, AWT contains aTextArea Class. It is used for displaying multiple-line text.

Example Program
import [Link].*; // Import AWT package
public class TextAreaDemo
{
public static void main(String[] args)
{
Frame f = new Frame("TextArea Example"); // Create frame
TextArea ta = new TextArea("Type your comments here..."); // Multi-line area
[Link](60, 80, 250, 100); // Set position and size

[Link](ta); // Add text area to frame


[Link](400, 250); // Frame size
[Link](null); // No layout manager
[Link](true); // Show frame
}
}
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).
Example program

import [Link].*; // Import AWT package


public class CheckboxDemo1
{
public static void main(String[] args)
{
Frame f = new Frame("Checkbox Example"); // Create frame

Checkbox c1 = new Checkbox("Yes", true); // Checked by default


[Link](100, 100, 80, 30); // Set position and size

Checkbox c2 = new Checkbox("No"); // Unchecked by default


[Link](100, 150, 80, 30);

[Link](c1); // Add first checkbox


[Link](c2); // Add second checkbox

[Link](300, 200); // Frame size


[Link](null); // Use no layout manager
[Link](true); // Show frame
}
}
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 [Link].*; // Import AWT package
public class ListDemo
{
public static void main(String[] args)
{
Frame f = new Frame("AWT List Example"); // Create frame

List list = new List(4); // Show 4 items at a time


[Link](80, 80, 150, 100); // Set position and size

[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link]("HTML");
[Link]("JavaScript");

[Link](list); // Add list to frame


[Link](300, 250); // Frame size
[Link](null); // No layout manager
[Link](true); // Show frame
}
}
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

import [Link].*; // Import AWT for GUI components.


public class MenuEx1
{
public static void main(String[] args)
{
Frame frame = new Frame("Simple Menu Example"); // Create a Frame with title
// Create menu bar
MenuBar menuBar = new MenuBar(); // Create a MenuBar to hold menus

// First main menu with a submenu


Menu m1 = new Menu("File"); // Create first main menu named "File"
[Link](new MenuItem("New")); // Add menu item "New" to File menu
[Link](new MenuItem("Open")); // Add menu item "Open" to File menu
Menu sm1 = new Menu("Save-as"); // Create a submenu "Save-as" under File menu
[Link](new MenuItem(".jpeg")); // Add submenu item ".jpeg" to Save-as
[Link](new MenuItem(".png")); // Add submenu item ".png" to Save-as
[Link](sm1); // Add the submenu to the File menu
// Second main menu with a submenu
Menu m2 = new Menu("Edit"); // Create second main menu named "Edit"
[Link](new MenuItem("Cut")); // Add menu item "Cut" to Edit menu
[Link](new MenuItem("Copy")); // Add menu item "Copy" to Edit menu
// Add menus to menu bar
[Link](m1); // Add File menu to the menu bar
[Link](m2); // Add Edit menu to the menu bar
// Set menu bar to frame
[Link](menuBar); // Attach the menu bar to the frame
[Link](300, 200); // Set size of the frame (width, height)
[Link](true); // Make the frame visible on the screen
}
}

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


public void init(): is used to initialized the Applet. It is invoked only once.

public void start(): is invoked after the init() method or browser is


maximized. It is used to start the Applet.

public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.

public void destroy(): is used to destroy 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 different platform browsers.
[Link]
import [Link];
import [Link];
public class HelloWorld extends Applet
{
// Paint method to display text on applet window
public void paint(Graphics g)
{
[Link]("Hello, World!", 50, 50); // Draw "Hello, World!" at posi (50,50)
}
}

Compile using javac:


javac [Link]
Now you have to create an HTML File that Includes the Applet.
Using a text editor, create a file named [Link] in the same directory that contains
[Link].
<html>
<body>
<applet code="[Link]" width="300" height="200"></applet>
</body>
</html>

Run the program using appletviewer


appletviewer [Link]
Simple example of Applet by appletviewer
import [Link];
import [Link];

public class Welcome extends Applet


{
// Paint method to display text on applet window
public void paint(Graphics g)
{
[Link]("Welcome to Applet", 50, 50); // Draw "Welcome" at pos(50,50)
}
}
// appletviewer [Link]
/*
<applet code="[Link]" width="300" height="200"></applet>
*/

Compile and Run

javac [Link]
appletviewer [Link]

Displaying Graphics in Applet


[Link] class provides many methods for graphics programming. .

Example -[Link]
import [Link];
import [Link].*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
// Draw text in red
[Link]([Link]);
[Link]("Welcome", 50, 50);

// Draw shapes in red


[Link](20, 30, 20, 300);
[Link](70, 100, 30, 30);
[Link](170, 100, 30, 30);
[Link](70, 200, 30, 30);

// Draw shapes in pink


[Link]([Link]);
[Link](170, 200, 30, 30);
[Link](90, 150, 30, 30, 0, 270);
[Link](270, 150, 30, 30, 0, 180);
}
}
// appletviewer [Link]
/*
<applet code="[Link]" width="400" height="400"></applet>
*/

The [Link] 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.

Example of displaying image in applet


import [Link].*;
import [Link];
public class DisplayImage extends Applet
{
Image picture;
public void init() // Initialize the applet
{
picture = getImage(getDocumentBase(), "[Link]"); // Load image
}
public void paint(Graphics g) // Paint method to display the image
{
[Link](picture, 30, 20, this);
}
}

// appletviewer [Link]
/*
<applet code="[Link]" width="400" height="400"></applet>
*/
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
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 [Link].*;
import [Link].*;
import [Link].*;
public class AnAppletWithButtons extends Applet implements ActionListener
{
Button b1, b2;
public void init()
{
b1 = new Button("Button 1");
add(b1);
[Link](this);

b2 = new Button("Button 2");


add(b2);
[Link](this);
}
public void actionPerformed(ActionEvent e) { if ([Link]() == button1)
[Link]("Button 1 was pressed");
else
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

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
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. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]

[Link]
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 [Link].*;
import [Link].*;

public class FlowDemo1 {


public static void main(String[] args) {
JFrame frame = new JFrame("Flow Demo");
[Link](new FlowLayout([Link]));

// Add buttons 1 to 10
for (int i = 1; i <= 10; i++) {
[Link](new JButton("" + i));
}

[Link](400, 400);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

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


[Link].*;
import [Link].*;
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
[Link](b1,[Link]);
[Link](b2,[Link]);
[Link](b3,[Link]);
[Link](b4,[Link]);
[Link](b5,[Link]);
//Function to set size of the Frame [Link](300,
300);
//Function to set visible status of the frame
[Link](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 [Link].*; import


[Link].*;

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*");

[Link](box1);
[Link](box2);
[Link](box3);
[Link](box4);
[Link](box5);
[Link](box6);
[Link](box7);
[Link](box8);
[Link](box9);

[Link](new GridLayout(3,3));
[Link](500,500); [Link](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 [Link] 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