KEMBAR78
Unit-V (Oop Using Java) | PDF | Model–View–Controller | Object Oriented Programming
0% found this document useful (0 votes)
111 views53 pages

Unit-V (Oop Using Java)

The document provides an overview of GUI programming with Java Swing, covering key concepts such as MVC architecture, layout managers, and event handling. It includes examples of various Swing components like JFrame, JPanel, JButton, JTextField, JCheckBox, JRadioButton, and JComboBox, along with their functionalities. Additionally, it explains the MVC design pattern, its advantages, and provides a complete code example demonstrating its implementation.

Uploaded by

Varaprasad Mella
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)
111 views53 pages

Unit-V (Oop Using Java)

The document provides an overview of GUI programming with Java Swing, covering key concepts such as MVC architecture, layout managers, and event handling. It includes examples of various Swing components like JFrame, JPanel, JButton, JTextField, JCheckBox, JRadioButton, and JComboBox, along with their functionalities. Additionally, it explains the MVC design pattern, its advantages, and provides a complete code example demonstrating its implementation.

Uploaded by

Varaprasad Mella
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/ 53

UNIT-V

GUI Programming with Swing- Introduction, MVC architecture, components, containers.


Understanding Layout Managers - Flow Layout, Border Layout, Grid Layout, Card Layout, Grid Bag
Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event
classes, Handling mouse and keyboard events, Adapter classes, Inner classes, Anonymous Inner
classes

SWINGS
Introduction: Java Swing are 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.
Hierarchy of Java Swing classes

The hierarchy of java swing API is given below..

Example swing prog:


import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height

B V RAJU COLLEGE-OOP USING JAVA Page 1


f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

JFrame:
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Ex:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Jpanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
button.setText("Button");
panel.add(label);

B V RAJU COLLEGE-OOP USING JAVA Page 2


panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

JApplet:
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.
Ex:
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{ JButton
b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);

B V RAJU COLLEGE-OOP USING JAVA Page 3


}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked only
once.
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>

JPanel: The JPanel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the JComponents class.
It doesn't have title bar.
Sy: public class JPanel extends JComponent implements Accessible

Ex:
import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");

B V RAJU COLLEGE-OOP USING JAVA Page 4


JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

MVC Architecture in Java


The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or application
shall consist of data model, presentation information and control information. The MVC
pattern needs all these components to be separated as different objects.

B V RAJU COLLEGE-OOP USING JAVA Page 5


What is the MVC Design Pattern?
The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using model
designs.
The MVC pattern architecture consists of three layers:
o Model: It represents the business layer of application. It is an object to carry the data that can
also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the data that the
model contains.
o Controller: It works on both the model and view. It is used to manage the flow of application,
i.e. data flow in the model object and to update the view whenever data is changed.

1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
o The extending and testing of application is easier.

B V RAJU COLLEGE-OOP USING JAVA Page 6


Example of the MVC Design Pattern
1. Model (Student class)
Represents the data (student’s name and roll number) and provides methods to access
and modify this data.

class Student {

private String rollNo;

private String name;

public String getRollNo() {

return rollNo;

public void setRollNo(String rollNo) {

this.rollNo = rollNo;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

2. View (StudentView class)


Represents how the data (student details) should be displayed to the user. Contains a method
(printStudentDetails) to print the student’s name and roll number.

class StudentView {

B V RAJU COLLEGE-OOP USING JAVA Page 7


public void printStudentDetails(String studentName, String studentRollNo) {

System.out.println("Student:");

System.out.println("Name: " + studentName);

System.out.println("Roll No: " + studentRollNo);

3. Controller (StudentController class)


Acts as an intermediary between the Model and the View. Contains references to the Model and
View objects. Provides methods to update the Model (e.g., setStudentName, setStudentRollNo ) and
to update the View (updateView).

class StudentController {

private Student model;

private StudentView view;

public StudentController(Student model, StudentView view) {

this.model = model;

this.view = view;

public void setStudentName(String name) {

model.setName(name);

public String getStudentName() {

return model.getName();

B V RAJU COLLEGE-OOP USING JAVA Page 8


public void setStudentRollNo(String rollNo) {

model.setRollNo(rollNo);

public String getStudentRollNo() {

return model.getRollNo();

public void updateView() {

view.printStudentDetails(model.getName(), model.getRollNo());

Complete code for the above example


Below is the complete code for the above example:

class Student {

private String rollNo;

private String name;

public String getRollNo() {

return rollNo;

public void setRollNo(String rollNo) {

this.rollNo = rollNo;

public String getName() {

B V RAJU COLLEGE-OOP USING JAVA Page 9


return name;

public void setName(String name) {

this.name = name;

class StudentView {

public void printStudentDetails(String studentName, String studentRollNo) {

System.out.println("Student:");

System.out.println("Name: " + studentName);

System.out.println("Roll No: " + studentRollNo);

class StudentController {

private Student model;

private StudentView view;

public StudentController(Student model, StudentView view) {

this.model = model;

this.view = view;

public void setStudentName(String name) {

model.setName(name);

B V RAJU COLLEGE-OOP USING JAVA Page 10


}

public String getStudentName() {

return model.getName();

public void setStudentRollNo(String rollNo) {

model.setRollNo(rollNo);

public String getStudentRollNo() {

return model.getRollNo();

public void updateView() {

view.printStudentDetails(model.getName(), model.getRollNo());

public class MVCPattern {

public static void main(String[] args) {

Student model = retriveStudentFromDatabase();

StudentView view = new StudentView();

StudentController controller = new StudentController(model, view);

controller.updateView();

controller.setStudentName("Vikram Sharma");

controller.updateView();

B V RAJU COLLEGE-OOP USING JAVA Page 11


}

private static Student retriveStudentFromDatabase() {

Student student = new Student();

student.setName("Lokesh Sharma");

student.setRollNo("15UCS157");

return student;

 Output

Student:

Name: Lokesh Sharma

Roll No: 15UCS157

Student:

Name: Vikram Sharma

Roll No: 15UCS157

Components in Swings:
Swing Framework contains a large set of components which provide rich functionalities
and allow high level of customization. All these components are lightweight components.
They all are derived from JComponent class. It supports the pluggable look and feel.
1. JButton:
JButton class provides functionality of a button. JButton supports ActionEvent. When a
button is pressed an ActionEvent is generated.
Example using JButton

B V RAJU COLLEGE-OOP USING JAVA Page 12


import
javax.swing.*;
import
java.awt.event.*;
import
java.awt.*;
public class testswing extends JFrame
{
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes
Button. JButton bt2 = new JButton("No");
//Creating a No
Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close
operation. setLayout(new FlowLayout()); //setting layout using FlowLayout
object setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to
frame. add(bt2); //adding No button
to frame. setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 13


JTextField:
JTextField is used for taking input of single line of text. It is most widely used text component.

Example using JTextField

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20);//creating JTextField.
add(jtf);//adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 14


JCheckBox:
JCheckBox class is used to create checkboxes in frame.

Example using JCheckBox

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}

public static void main(String[] args)


{
new Test();
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 15


JRadioButton:
Radio button is a group of related button in which only one can be selected. JRadioButton
class is used to create a radio button in Frames.
Example using JRadioButton

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JRadioButton jcb = new JRadioButton("A");//creating JRadioButton.
add(jcb);//adding JRadioButton to frame.
jcb = new JRadioButton("B");//creating JRadioButton.
add(jcb);//adding JRadioButton to frame.
jcb = new JRadioButton("C");//creating JRadioButton.
add(jcb);//adding JRadioButton to frame.
jcb = new JRadioButton("none");
add(jcb);

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 16


JComboBox:
Combo box is a combination of text fields and drop-down list. JComboBox component is
used to create a combo box in Swing.
Example using JComboBox

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.
add(jc); //adding JComboBox to frame.

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 17


Containers - Java Swing
Containers are an integral part of SWING GUI components. A container provides a space
where a component can be located. A Container in AWT is a component itself and it
provides the capability to add a component to itself.
 Sub classes of Container are called as Container. For example, JPanel, JFrame and
JWindow.
 Container can add only a Component to itself.
 A default layout is present in each container which can be overridden using setLayout
method.

SWING Containers
Following is the list of commonly used containers while designing GUI using SWING.
1. Panel: JPanel is the simplest container. It provides space in which any other component can be
placed, including other panels.
2. Frame: A JFrame is a top-level window with a title and a border.
3. Window: A JWindow object is a top-level window with no borders and no menubar.

Introduction-JPanel:
The class JPanel is a generic lightweight container.
Class Constructors:
1. JPanel(): Creates a new JPanel with a double buffer and a flow layout.
2. JPanel(boolean isDoubleBuffered): Creates a new JPanel with FlowLayout and the specified
buffering strategy.
3. JPanel(LayoutManager layout): Creates a new buffered JPanel with the specified layout
manager.
4. JPanel(LayoutManager layout, boolean isDoubleBuffered): Creates a new JPanel with the
specified layout manager and buffering strategy.
Class Methods:
1. AccessibleContext getAccessibleContext(): Gets the AccessibleContext associated with this

B V RAJU COLLEGE-OOP USING JAVA Page 18


JPanel.
2. PanelUI getUI(): Returns the look and feel (L&F) object that renders this component.
3. String getUIClassID(): Returns a string that specifies the name of the L&F class which renders
this component.
4. protected String paramString(): Returns a string representation of this JPanel.
5. void setUI(PanelUI ui): Sets the look and feel (L&F) object that renders this component.
6. void updateUI(): Resets the UI property with a value from the current look and feel.
JPanel Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingContainerDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;

public SwingContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingContainerDemo swingContainerDemo = new SwingContainerDemo();
swingContainerDemo.showJPanelDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
msglabel = new JLabel("Welcome to CodersArts SWING blog", JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());

B V RAJU COLLEGE-OOP USING JAVA Page 19


mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showJPanelDemo(){
headerLabel.setText("Container in action: JPanel");
JPanel panel = new JPanel();
panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
Output:

Introduction-JFrame:
The class JFrame is an extended version of java.awt.Frame that adds support for the
JFC/Swing component architecture.

Field
Following are the fields for java.awt.Component class −
 protected AccessibleContext accessibleContext −The accessible context property.
 static int EXIT_ON_CLOSE − The exit application default window close operation.

B V RAJU COLLEGE-OOP USING JAVA Page 20


 protected JRootPane rootPane − The JRootPane instance that manages the contentPane
and optional menuBar for this frame, as well as the glassPane.
 protected boolean rootPaneCheckingEnabled − If true then calls to add and setLayout will
be forwarded to the contentPane.
Class Constructors:
 JFrame(): Constructs a new frame that is initially invisible.
 JFrame(GraphicsConfiguration gc): Creates a Frame in the specified GraphicsConfiguration
of a screen device and a blank title.
 JFrame(String title): Creates a new, initially invisible Frame with the specified title.
 JFrame(String title, GraphicsConfiguration gc): Creates a JFrame with the specified title and
the specified GraphicsConfiguration of a screen device.
Class Methods:
1. Component getGlassPane(): Returns the glassPane object for this frame.
2. Graphics getGraphics(): Creates a graphics context for this component.
3. JMenuBar getJMenuBar(): Returns the menubar set on this frame.
4. JLayeredPane getLayeredPane(): Returns the layeredPane object for this frame.
5. JRootPane getRootPane(): Returns the rootPane object for this frame.

JFrame Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingContainerDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;

public SwingContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingContainerDemo swingContainerDemo = new SwingContainerDemo();
swingContainerDemo.showJFrameDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

B V RAJU COLLEGE-OOP USING JAVA Page 21


public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
msglabel = new JLabel("Welcome to CodersArts.", JLabel.CENTER);

controlPanel = new JPanel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showJFrameDemo(){
headerLabel.setText("Container in action: JFrame");
final JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
frame.add(msglabel);

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
frame.dispose();
}
});
JButton okButton = new JButton("Open a Frame");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("A Frame shown to the user.");
frame.setVisible(true);
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
}
Output:

B V RAJU COLLEGE-OOP USING JAVA Page 22


Introduction-JWindow
The class JWindow is a container that can be displayed but does not have the title bar or window-
management buttons.
Field
Following are the fields for java.awt.Component class −
 protected AccessibleContext accessibleContext − The accessible context property.
 protected JRootPane rootPane − The JRootPane instance that manages the contentPane and
optional menuBar for this frame, as well as the glassPane.
 protected boolean rootPaneCheckingEnabled − If true then calls to add and setLayout will be
forwarded to the contentPane.
Class Constructors
 JWindow(): Creates a window with no specified owner.
 JWindow(Frame owner): Creates a window with the specified owner frame.
 JWindow(GraphicsConfiguration gc): Creates a window with the specified
GraphicsConfiguration of a screen device.
 JWindow(Window owner): Creates a window with the specified owner window.
 JWindow(Window owner, GraphicsConfiguration gc): Creates a window with the specified
owner window and GraphicsConfiguration of a screen device.
Class Methods
 protected void addImpl(Component comp, Object constraints, int index): Adds the
specified child Component.
 protected JRootPane createRootPane(): Called by the constructor methods to create the
default rootPane.
 AccessibleContext getAccessibleContext(): Gets the AccessibleContext associated with this
JWindow.
 Container getContentPane(): Returns the Container which is the contentPane for this
window.

B V RAJU COLLEGE-OOP USING JAVA Page 23


JWindow Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {


private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;

public SwingContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingContainerDemo swingContainerDemo = new SwingContainerDemo();
swingContainerDemo.showJWindowDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showJWindowDemo(){
headerLabel.setText("Container in action: JWindow");
final MessageWindow window = new MessageWindow(

B V RAJU COLLEGE-OOP USING JAVA Page 24


mainFrame, "Welcome to CodersArts.");
JButton okButton = new JButton("Open a Window");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.setVisible(true);
statusLabel.setText("A Window shown to the user.");
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
class MessageWindow extends JWindow{
private String message;
public MessageWindow(JFrame parent, String message) {
super(parent);
this.message = message;
setSize(400, 400);
setLocationRelativeTo(parent);
}
public void paint(Graphics g) {
super.paint(g);
g.drawRect(0,0,getSize().width - 1,getSize().height - 1);
g.drawString(message,50,150);
}
}
}

Output:

B V RAJU COLLEGE-OOP USING JAVA Page 25


Layout Managers:
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.
There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

1. Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of
frame or window.
Ex:
import
java.awt.*;
import
javax.swing.*;
public class
Border { JFrame
f;
Border(){
f=new JFrame();
JButton b1=new
JButton("NORTH");; JButton
b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new
JButton("CENTER");;

B V RAJU COLLEGE-OOP USING JAVA Page 26


f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

2. Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Ex:
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{ JFrame f;
MyGridLayout(){ f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");

B V RAJU COLLEGE-OOP USING JAVA Page 27


JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3
columns f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}

3. Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.
Ex:
import java.awt.*;

B V RAJU COLLEGE-OOP USING JAVA Page 28


import javax.swing.*;
public class MyFlowLayout{ JFrame f;
MyFlowLayout()
{ f=new
JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5"); f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}

4. Java BoxLayout
The BoxLayout is used to arrange the components either vertically or
horizontally. Ex:
import java.awt.*;

B V RAJU COLLEGE-OOP USING JAVA Page 29


import javax.swing.*;
public class BoxLayoutExample1 extends Frame
{ Button buttons[];
public BoxLayoutExample1 ()
{ buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

Example of BoxLayout class with X-AXIS

B V RAJU COLLEGE-OOP USING JAVA Page 30


5. Java CardLayout
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout
Ex:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3; Container c; CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple"); b2=new
JButton("Boy"); b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent
e) { card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new
CardLayoutExample(); cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);

B V RAJU COLLEGE-OOP USING JAVA Page 31


}
}

6. Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display
area. Each component associates an instance of GridBagConstraints. With the help of
constraints object we arrange component's display area on the grid. The GridBagLayout
manages each component's minimum and preferred sizes in order to determine
component's size.
Ex:
import java.awt.Button;
import
java.awt.GridBagConstraints;
import
java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{

public static void main(String[] args) {


GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;

B V RAJU COLLEGE-OOP USING JAVA Page 32


gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill =
GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 33


7. GroupLayout
As the name implies, GroupLayout manages the layout of groups and places them in
different positions. It consists of two type of groups: sequential and parallelgroup.
For sequential group arrangement, the components are placed very similar to BoxLayout
or FlowLayout, one after another. The position of each component is according to the order
of the component.
For parallel group arrangement, components are placed on top of each other at the same
place. They can be baseline-, top- or bottom-aligned at vertical, or left-, right-, center-aligned
at horizontal axis.
In the following example, four buttons are created with button 1, 2, 3 are
following the sequential pattern, while button 3, 4 are grouped together.
GroupLayoutExample.java
package javaCodeGeeks;
import javax.swing.GroupLayout;
/*

* A Java swing GroupLayout example


*/
import
javax.swing.JButton;
import
javax.swing.JFrame;
import
javax.swing.JPanel;
public class GroupLayoutExample {
public static void main(String[]
args) {
// Create and set up a frame window
JFrame.setDefaultLookAndFeelDecorated(
true);
JFrame frame = new JFrame("Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Define new buttons with different width on help of
the --- JButton jb1 = new JButton("1");
JButton jb2 = new
JButton("2"); JButton jb3
= new JButton("3");
JButton jb4 = new
JButton("4");
// Define the panel to hold the

B V RAJU COLLEGE-OOP USING JAVA Page 34


buttons JPanel panel = new
JPanel(); panel.setSize(300, 300);
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
// Set for horizontal and vertical group
layout.setHorizontalGroup(layout.createSequentialGroup().addComponent(jb1).addCo
mponent(jb2)
.addGroup(layout.createSequentialGroup().addGroup(layout
.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(jb3).addC
omp onent(jb4))));
layout.setVerticalGroup(layout.createSequentialGroup().addComponent(jb1).addComp
onent(j b2).addComponent(jb3).addComponent(jb4));
frame.add(panel);
frame.pack();
frame.setVisible(tr
ue);
}
}

8. Java SpringLayout
Similar to the name,Spring Layout manages the layout of its children/Spring. Every child of
Spring object controls the vertical or horizontal distance between the two components edges.
In addition, for every child, it has exactly one set of constraint associated with it.
In the example below, we have constructed a label with a textfield and put constraints on
the edge of the two components.
Ex:
package javaCodeGeeks;
/*
* A Java swing SpringLayout example

B V RAJU COLLEGE-OOP USING JAVA Page 35


*/
import javax.swing.JLabel;
import
javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import
javax.swing.SpringLayout;
public class SpringLayoutExample {
public static void main(String[]
args) {
// Create and set up a frame window
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Define the panel to hold the
components JPanel panel = new
JPanel();
SpringLayout layout = new SpringLayout();
JLabel label = new JLabel("Label: ");
JTextField text = new JTextField("Text field", 15);
panel.setSize(300, 300);
panel.setLayout(layout);
panel.add(label);
panel.add(text);
// Put constraint on components
layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.WEST, text, 5, SpringLayout.EAST, label);
layout.putConstraint(SpringLayout.NORTH, text, 5, SpringLayout.NORTH, panel);
// Set the window to be visible as the default to be false
frame.add(panel);
frame.pack();
frame.setVisible(tr
ue);
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 36


9. ScrollPaneLayout:
The layout manager used by JScrollPane. JScrollPaneLayout is responsible for nine
components: a viewport, two scrollbars, a row header, a column header, and four "corner"
components.
Ex:
import
javax.swing.ImageIcon;
import
javax.swing.JFrame;
import javax.swing.JLabel;
import
javax.swing.JScrollPane;
public class ScrollPaneDemo extends JFrame
{
public ScrollPaneDemo() {
super("ScrollPane Demo");
ImageIcon img = new ImageIcon("child.png");
JScrollPane png = new JScrollPane(new JLabel(img));
getContentPane().add(png);
setSize(300,250);
setVisible(true);
}
public static void main(String[] args) {
new ScrollPaneDemo();
}

B V RAJU COLLEGE-OOP USING JAVA Page 37


J Scroll Pane: Just now discussed
…. Split Pane:
JSplitPane is used to divide two components. The two components are divided based on
the look and feel implementation, and they can be resized by the user.
The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using JSplitPane.VERTICAL_SPLIT. When the
user is resizing the components the minimum size of the components is used to determine
the maximum/minimum position the components can be set to.
Ex:
import java.awt.FlowLayout;
import java.awt.Panel;
import
javax.swing.JComboBox;
import javax.swing.JFrame;
import
javax.swing.JSplitPane;
public class
JSplitPaneExample {
private static void createAndShow() {
// Create and set up the window.
final JFrame frame = new JFrame("JSplitPane Example");

// Display the window.


frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new
FlowLayout()); String[] option1 = {
"A","B","C","D","E" };

B V RAJU COLLEGE-OOP USING JAVA Page 38


JComboBox box1 = new JComboBox(option1);
String[] option2 = {"1","2","3","4","5"};
JComboBox box2 = new JComboBox(option2);
Panel panel1 = new Panel();
panel1.add(box1);
Panel panel2 = new Panel();
panel2.add(box2);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// panel1, panel2);
frame.getContentPane().add(splitPane);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShow();
}
}
}
}

JTabbed Pane:
The JTabbedPane class is used to switch between a group of components by clicking on a
tab with a given title or icon. It inherits JComponent class.

B V RAJU COLLEGE-OOP USING JAVA Page 39


Syntax:
public class JTabbedPane extends JComponent implements Serializable, Accessible,
SwingConst ants
Ex:
import javax.swing.*;

public class TabbedPaneExample {


JFrame f;
TabbedPaneExample()
{ f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new
JPanel(); JPanel
p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3); f.add(tp);
f.setSize(400,400);
f.setLayout(null); f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();

B V RAJU COLLEGE-OOP USING JAVA Page 40


Introduction

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 keyboard, selecting an item from list, scrolling the page are the activities
that causes an event to happen.
Types of Event
The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of user. They
are generated as consequences of a person interacting with the graphical
components in Graphical User Interface. For example, clicking on a button, moving
the mouse, entering a character through keyboard, selecting an item from list,
scrolling the page etc.
 Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
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. The
Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide classes for
source object.
 Listener - It is also known as event handler. Listener is responsible for generating
response to an event. Listener is also an object. Listener waits until it receives an
event. Once the event is received , the listener process the event and then returns.
Event deligation
Event handling code deals with events generated by GUI user interaction. The best
practices for coding event handlers are event delegation model.
The event delegation model comprises three elements:

 Event source

 Event listener

 Adapter

B V RAJU COLLEGE-OOP USING JAVA Page 41


Event source
An event source is a component, such as a GUI component, that generates an event.
The event source can be generated by any type of user interaction.
In the event delegation model, a class represents each event type. Event objects are
all defined in the java.util.Event Object subclasses.
Event listener
Event listeners are objects that receive notification of an event. When an event is
fired, an event object is passed as an argument to the relevant listener object
method. The listener object then handles the event.
All listeners are implementations of the EventListener interface or one of its
subinterfaces. The Java API provides a predefined listener interface.
Adapter
Adapters are abstract classes that implement listener interfaces using predefined
methods. These are provided for convenience.

Java.awt.event description
It Provides interfaces and classes for dealing with different types of events fired by AWT
components.

Interface Description

ActionListener The listener interface for receiving action events.

AdjustmentListener The listener interface for receiving adjustment events.

AWTEventListener The listener interface for receiving notification of events dispatched to


objects instances of Component or MenuComponent or their subclasses.

ComponentListener The listener interface for receiving component events.

ContainerListener The listener interface for receiving container events.

FocusListener The listener interface for receiving keyboard focus events on a component.

HierarchyBoundsListener The listener interface for receiving ancestor moved and resized events.

HierarchyListener The listener interface for receiving hierarchy changed events.

InputMethodListener The listener interface for receiving input method events.

ItemListener The listener interface for receiving item events.

B V RAJU COLLEGE-OOP USING JAVA Page 42


KeyListener The listener interface for receiving keyboard events (keystrokes).

MouseListener The listener interface for receiving "interesting" mouse events (press,
release, c enter, and exit) on a component.

MouseMotionListener The listener interface for receiving mouse motion events on a component.

MouseWheelListener The listener interface for receiving mouse wheel events on a component.

TextListener The listener interface for receiving text events.

WindowFocusListener The listener interface for receiving WindowEvents,


including WINDOW_GAINED_FOCUSand WINDOW_LOST_FOCUS even
WindowListener The listener interface for receiving window events.

WindowStateListener The listener interface for receiving window state events.

Sources of Events

Event Listerners
The Event listener represent the interfaces responsible to handle events. Java provides us
various Event listener classes
AWT Event Listener Interfaces:
Following is the list of commonly used event listeners.

B V RAJU COLLEGE-OOP USING JAVA Page 43


Sr. Control & Description
No.

1 ActionListener
This interface is used for receiving the action events.

2 ComponentListener
This interface is used for receiving the component events.

3 ItemListener
This interface is used for receiving the item events.

4 KeyListener
This interface is used for receiving the key events.

5 MouseListener
This interface is used for receiving the mouse events.

6 TextListener
This interface is used for receiving the text events.

7 WindowListener
This interface is used for receiving the window events.

8 AdjustmentListener
This interface is used for receiving the adjusmtent events.

9 ContainerListener

This interface is used for receiving the container events.

10 MouseMotionListener
This interface is used for receiving the mouse motion events.

B V RAJU COLLEGE-OOP USING JAVA Page 44


11 FocusListener
This interface is used for receiving the focus events

Adapter Classes
Adapter classes provide an implementation of listener interfaces. When you inherit the adapter
class implementation for all methods is not mandatory. Thus writing excess code is saved.
These adapter classes can be found in java.awt.event, java.awt.dnd and javax.swing.event
packages. Some of the common adapter classes with corresponding listener interfaces are given
below.
 java.awt.event

 java.awt.dnd
 javax.swing.event

java.awt.event Adapter classes:

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

B V RAJU COLLEGE-OOP USING JAVA Page 45


HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes:

Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes:

Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Inner Classes
Inner class means one class which is a member of another class. There are basically four types of
inner classes in java.
1) Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes

B V RAJU COLLEGE-OOP USING JAVA Page 46


1) Nested Inner class can access any private instance variable of outer class. Like any other
instance variable, we can have access modifier private, protected, public and default
modifier. Like class, interface can also be nested and can have access specifiers.
Following example demonstrates a nested class.
class Outer {
// Simple nested inner
class class Inner {
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output:
In a nested class method

2) Method Local inner classes


Inner class can be declared within a method of an outer class. In the following example, Inner is
an inner class in outerMethod().
class Outer {
void outerMethod() {
System.out.println("insideouterMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("insideinnerMethod");
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 47


Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo {
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}

Output
Inside outerMethod
Inside innerMethod

3) Static nested classes


Static nested classes are not technically an inner class. They are like a static member of outer
class. class Outer {
private static void outerMethod() {
System.out.println("inside
outerMethod");
}
// A static inner class
static class Inner {
public static void main(String[] args) {
System.out.println("inside inner class Method");
outerMethod();
}
}

}
Output
inside inner class Method
inside outerMethod

B V RAJU COLLEGE-OOP USING JAVA Page 48


4) Anonymous inner classes
Anonymous inner classes are declared without any name at all. They are created
As subclass of specified type
Ex:
class Demo {
void show()
{
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as
base class static Demo d = new
Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
}
public static void main(String[] args){
d.show();
}
}
Output
i am in show method of super class
i am in Flavor1Demo class

Handling mouse and keyboard events


Handle mouse events, we must implement one of the appropriate interfaces as follows:
1) MouseListener
2) MouseMotionListener
3) MouseWheelListener
If any one of the above interfaces is implemented, we must provide implementations for all the
methods available in that interface.
Methods available in “MouseListener” interface are:
1) mouseClicked()
2) mousePressed()
3) mouseReleased()

B V RAJU COLLEGE-OOP USING JAVA Page 49


4) mouseEntered()
5) mouseExited()

Methods available in “MouseMotionListener” interface are:


1) mouseMoved()
2) mouseDragged()
Methods available in “MouseWheelListener” are:
1) mouseWheelMoved()
We can get the x-coordinate and y-coordinate where the mouse is clicked by using two
methods available in “MouseEvent” class. Those methods are:
1) int getX() – To get the x-coordinate
2) int getY() – To get the y-coordinate

Java MouseListener Example


import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

B V RAJU COLLEGE-OOP USING JAVA Page 50


Output:

Handling Keyboard Events:

To handle keyboard events, we must implement the “KeyListener” interface.


When the “KeyListener” interface is implemented, we must provide implementations for three
methods available in that interface. They are:
1) keyPressed()
2) keyReleased()
3) keyTyped()
To get the character, when the keyTyped() event occurs, we use the method:
1)char getKeyChar()

Java KeyListener Example


//Java program to demonstrate keyPressed,
// keyReleased and keyTyped method
import java.awt.*;
import java.awt.event.*;

B V RAJU COLLEGE-OOP USING JAVA Page 51


public class KeyListenerExample extends Frame implements KeyListener {

private TextField textField;


private Label displayLabel;

// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());

// Create and add a TextField for text input


textField = new TextField(20);
textField.addKeyListener(this);
add(textField);

// Create and add a Label to display typed text


displayLabel = new Label("Typed Text: ");
add(displayLabel);

// Ensure the frame can receive key events


setFocusable(true);
setFocusTraversalKeysEnabled(false);

// Make the frame visible


setVisible(true);
}

// Implement the keyPressed method


@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("Key Pressed: " + KeyEvent.getKeyText(keyCode));
}

// Implement the keyReleased method


@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("Key Released: " + KeyEvent.getKeyText(keyCode));
}

// Implement the keyTyped method


@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
System.out.println("Key Typed: " + keyChar);

B V RAJU COLLEGE-OOP USING JAVA Page 52


displayLabel.setText("Typed Text: " + textField.getText() + keyChar);
}

public static void main(String[] args) {


new KeyListenerExample();
}
}

Output:

B V RAJU COLLEGE-OOP USING JAVA Page 53

You might also like