Chapter 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 63

Chapter One

GUI and Event Handling


GUI(Graphical User Interface) Used to design user friendly systems.
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as
message dialog box, confirm dialog box and input dialog box. These dialog
boxes are used to display information or get input from the user. The
JOptionPane class inherits JComponent class.
JOptionPane class declaration
1. public class JOptionPane extends JComponent implements Accessible
Common Constructors of JOptionPane class
Constructor Description
JOptionPane() It is used to create a JOptionPane with a test
message.
JOptionPane(Object It is used to create an instance of JOptionPane
message) to display a message.
JOptionPane(Object It is used to create an instance of JOptionPane
message, int messageType to display a message with specified message
type and default options.
Common Methods of JOptionPane class
Methods Description
JDialog createDialog(String title) It is used to create and return a
new parentless JDialog with the
specified title.
static void showMessageDialog(Component It is used to create an
parentComponent, Object message) information-message dialog titled
"Message".
static void showMessageDialog(Component It is used to create a message
parentComponent, Object message, String dialog with given title and
title, int messageType) messageType.
static int showConfirmDialog(Component It is used to create a dialog with
parentComponent, Object message) the options Yes, No and Cancel;
with the title, Select an Option.
static String showInputDialog(Component It is used to show a question-
parentComponent, Object message) message dialog requesting input
from the user parented to
parentComponent.
void setInputValue(Object newValue) It is used to set the input value
that was selected or input by the
user.
Java JOptionPane Example: showMessageDialog()
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Output:
Java JOptionPane Example: showInputDialog()
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=JOptionPane.showInputDialog(f,"Enter Name");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Output:

Java JOptionPane Example: showConfirmDialog()


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class OptionPaneExample extends WindowAdapter{
4. JFrame f;
5. OptionPaneExample(){
6. f=new JFrame();
7. f.addWindowListener(this);
8. f.setSize(300, 300);
9. f.setLayout(null);
10. f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
11. f.setVisible(true);
12. }
13. public void windowClosing(WindowEvent e) {
14. int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
15. if(a==JOptionPane.YES_OPTION){
16. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }
18. }
19. public static void main(String[] args) {
20. new OptionPaneExample();
21. }
22. }
Output:

Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User
Interface (GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
Why AWT is platform independent?
In simple words, an AWT application will look like a windows application in
Windows OS whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.

Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore
we can add a container inside container.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window. We need to create
an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It
is generic container for holding the components. It can have other components
like button, text field etc. An instance of Panel class creates a container, in
which we can add components.
Frame
The Frame is the container that contain title bar and border and can have
menu bars. It can have other components like button, text field, scrollbar etc.
Frame is most widely used container while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
public void setSize(int width,int Sets the size (width and height) of the
height) component.
public void Defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean Changes the visibility of the component,
status) by default false.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to create
a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here,
we are showing Button component on the Frame.
AWTExample1.java
1. // importing Java AWT class
2. import java.awt.*;
3. // extending Frame class to our class AWTExample1
4. public class AWTExample1 extends Frame {
5. // initializing using constructor
6. AWTExample1() {
7. // creating a button
8. Button b = new Button("Click Me!!");
9. // setting button position on screen
10. b.setBounds(30,100,80,30);
11. // adding button into frame
12. add(b);
13. // frame size 300 width and 300 height
14. setSize(300,300);
15. // setting the title of Frame
16. setTitle("This is our basic AWT example");
17. // no layout manager
18. setLayout(null);
19. // now frame will be visible, by default it is not visible
20. setVisible(true);
21. }
22. // main method
23. public static void main(String args[]) {
24. // creating instance of Frame class
25. AWTExample1 f = new AWTExample1();
26. }
27. }
The setBounds(int x-axis, int y-axis, int width, int height) method is used in
the above example that sets the position of the awt button.
Output:

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame
class. Here, we are creating a TextField, Label and Button component on the
Frame.
AWTExample2.java
1. // importing Java AWT class
2. import java.awt.*;
3.
4. // class AWTExample2 directly creates instance of Frame class
5. class AWTExample2 {
6. // initializing using constructor
7. AWTExample2() {
8. // creating a Frame
9. Frame f = new Frame();
10. // creating a Label
11. Label l = new Label("Employee id:");
12. // creating a Button
13. Button b = new Button("Submit");
14. // creating a TextField
15. TextField t = new TextField();
16. // setting position of above components in the frame
17. l.setBounds(20, 80, 80, 30);
18. t.setBounds(20, 100, 80, 30);
19. b.setBounds(100, 100, 80, 30);
20. // adding components into frame
21. f.add(b);
22. f.add(l);
23. f.add(t);
24. // frame size 300 width and 300 height
25. f.setSize(400,300);
26.
27. // setting the title of frame
28. f.setTitle("Employee info");
29. // no layout
30. f.setLayout(null);
31. // setting visibility of frame
32. f.setVisible(true);
33. }
34. // main method
35. public static void main(String args[]) {
36. // creating instance of Frame class
37. AWTExample2 awt_obj = new AWTExample2();
38. }
39. }
Output:

Java Swing
Java Swing tutorial 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


There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
1) AWT components are platform- Java swing components are
dependent. platform-independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable Swing supports pluggable look and
look and feel. feel.
4) AWT provides less components Swing provides more powerful
than Swing. components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given
below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int sets size of the component.
height)
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean b) sets the visibility of the component. It is
by default false.
Java Swing Examples
There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other
method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding
it on the JFrame object inside the main() method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5. JButton b=new JButton("click");//creating instance of JButton
6. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
7. f.add(b);//adding button in JFrame
8. f.setSize(400,500);//400 width and 500 height
9. f.setLayout(null);//using no layout managers
10. f.setVisible(true);//making the frame visible
11. }
12. }
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call
inside the java constructor.
File: Simple.java
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);
8. f.add(b);//adding button in JFrame
9. f.setSize(400,500);//400 width and 500 height
10. f.setLayout(null);//using no layout managers
11. f.setVisible(true);//making the frame visible
12. }
13. public static void main(String[] args) {
14. new Simple();
15. }
16. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above
example that sets the position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance
of JFrame class explicitly.
File: Simple2.java
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}

BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
The Java LayoutManagers facilitates us to control the positioning and size of
the components in GUI forms. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are the following
classes that represent 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.
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 a frame or window. The BorderLayout provides
five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
 BorderLayout(): creates a border layout but with no gaps between the
components.
 BorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border
5. {
6. JFrame f;
7. Border()
8. {
9. f = new JFrame();
10.
11. // creating buttons
12. JButton b1 = new JButton("NORTH");; // the button will be lab
eled as NORTH
13. JButton b2 = new JButton("SOUTH");; // the button will be lab
eled as SOUTH
14. JButton b3 = new JButton("EAST");; // the button will be labele
d as EAST
15. JButton b4 = new JButton("WEST");; // the button will be label
ed as WEST
16. JButton b5 = new JButton("CENTER");; // the button will be la
beled as CENTER
17.
18. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the Nor
th Direction
19. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the So
uth Direction
20. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East
Direction
21. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West
Direction
22. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the C
enter
23.
24. f.setSize(300, 300);
25. f.setVisible(true);
26. }
27. public static void main(String[] args) {
28. new Border();
29. }
30. }
Output:

Example of BorderLayout class: Using BorderLayout(int hgap, int vgap)


constructor
The following example inserts horizontal and vertical gaps between buttons
using the parameterized constructor BorderLayout(int hgap, int gap)
FileName: BorderLayoutExample.java
1. // import statement
2. import java.awt.*;
3. import javax.swing.*;
4. public class BorderLayoutExample
5. {
6. JFrame jframe;
7. // constructor
8. BorderLayoutExample()
9. {
10. // creating a Frame
11. jframe = new JFrame();
12. // create buttons
13. JButton btn1 = new JButton("NORTH");
14. JButton btn2 = new JButton("SOUTH");
15. JButton btn3 = new JButton("EAST");
16. JButton btn4 = new JButton("WEST");
17. JButton btn5 = new JButton("CENTER");
18. // creating an object of the BorderLayout class using
19. // the parameterized constructor where the horizontal gap is 2
0
20. // and vertical gap is 15. The gap will be evident when buttons
are placed
21. // in the frame
22. jframe.setLayout(new BorderLayout(20, 15));
23. jframe.add(btn1, BorderLayout.NORTH);
24. jframe.add(btn2, BorderLayout.SOUTH);
25. jframe.add(btn3, BorderLayout.EAST);
26. jframe.add(btn4, BorderLayout.WEST);
27. jframe.add(btn5, BorderLayout.CENTER);
28. jframe.setSize(300,300);
29. jframe.setVisible(true);
30. }
31. // main method
32. public static void main(String argvs[])
33. {
34. new BorderLayoutExample();
35. }
36. }
Output:

Java BorderLayout: Without Specifying Region


The add() method of the JFrame class can work even when we do not specify
the region. In such a case, only the latest component added is shown in the
frame, and all the components added previously get discarded. The latest
component covers the whole area. The following example shows the same.
FileName: BorderLayoutWithoutRegionExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4. public class BorderLayoutWithoutRegionExample
5. {
6. JFrame jframe;
7. // constructor
8. BorderLayoutWithoutRegionExample()
9. {
10. jframe = new JFrame();
11. JButton btn1 = new JButton("NORTH");
12. JButton btn2 = new JButton("SOUTH");
13. JButton btn3 = new JButton("EAST");
14. JButton btn4 = new JButton("WEST");
15. JButton btn5 = new JButton("CENTER");
16. // horizontal gap is 7, and the vertical gap is 7
17. // Since region is not specified, the gaps are of no use
18. jframe.setLayout(new BorderLayout(7, 7));
19. // each button covers the whole area
20. // however, the btn5 is the latest button
21. // that is added to the frame; therefore, btn5
22. // is shown
23. jframe.add(btn1);
24. jframe.add(btn2);
25. jframe.add(btn3);
26. jframe.add(btn4);
27. jframe.add(btn5);
28. jframe.setSize(300,300);
29. jframe.setVisible(true);
30. }
31. // main method
32. public static void main(String argvs[])
33. {
34. new BorderLayoutWithoutRegionExample();
35. }
36. }
Output:

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular
grid. One component is displayed in each rectangle.
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 of GridLayout class: Using GridLayout() Constructor
The GridLayout() constructor creates only one row. The following example
shows the usage of the parameterless constructor.
FileName: GridLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class GridLayoutExample
6. {
7. JFrame frameObj;
8.
9. // constructor
10. GridLayoutExample()
11. {
12. frameObj = new JFrame();
13.
14. // creating 9 buttons
15. JButton btn1 = new JButton("1");
16. JButton btn2 = new JButton("2");
17. JButton btn3 = new JButton("3");
18. JButton btn4 = new JButton("4");
19. JButton btn5 = new JButton("5");
20. JButton btn6 = new JButton("6");
21. JButton btn7 = new JButton("7");
22. JButton btn8 = new JButton("8");
23. JButton btn9 = new JButton("9");
24.
25. // adding buttons to the frame
26. // since, we are using the parameterless constructor, therfore;
27. // the number of columns is equal to the number of buttons we
28. // are adding to the frame. The row count remains one.
29. frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
30. frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
31. frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
32.
33. // setting the grid layout using the parameterless constructor
34. frameObj.setLayout(new GridLayout());
35.
36.
37. frameObj.setSize(300, 300);
38. frameObj.setVisible(true);
39. }
40.
41. // main method
42. public static void main(String argvs[])
43. {
44. new GridLayoutExample();
45. }
46. }
Output:
Example of GridLayout class: Using GridLayout(int rows, int columns)
Constructor
FileName: MyGridLayout.java
1. import java.awt.*;
2. import javax.swing.*;
3. public class MyGridLayout{
4. JFrame f;
5. MyGridLayout(){
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. JButton b6=new JButton("6");
13. JButton b7=new JButton("7");
14. JButton b8=new JButton("8");
15. JButton b9=new JButton("9");
16. // adding buttons to the frame
17. f.add(b1); f.add(b2); f.add(b3);
18. f.add(b4); f.add(b5); f.add(b6);
19. f.add(b7); f.add(b8); f.add(b9);
20.
21. // setting grid layout of 3 rows and 3 columns
22. f.setLayout(new GridLayout(3,3));
23. f.setSize(300,300);
24. f.setVisible(true);
25. }
26. public static void main(String[] args) {
27. new MyGridLayout();
28. }
29. }
Output:

Example of GridLayout class: Using GridLayout(int rows, int columns, int


hgap, int vgap) Constructor
The following example inserts horizontal and vertical gaps between buttons
using the parameterized constructor GridLayout(int rows, int columns, int
hgap, int vgap).
FileName: GridLayoutExample1.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class GridLayoutExample1
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. GridLayoutExample1()
12. {
13. frameObj = new JFrame();
14.
15. // creating 9 buttons
16. JButton btn1 = new JButton("1");
17. JButton btn2 = new JButton("2");
18. JButton btn3 = new JButton("3");
19. JButton btn4 = new JButton("4");
20. JButton btn5 = new JButton("5");
21. JButton btn6 = new JButton("6");
22. JButton btn7 = new JButton("7");
23. JButton btn8 = new JButton("8");
24. JButton btn9 = new JButton("9");
25.
26. // adding buttons to the frame
27. // since, we are using the parameterless constructor, therefore;
28. // the number of columns is equal to the number of buttons we
29. // are adding to the frame. The row count remains one.
30. frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
31. frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
32. frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
33. // setting the grid layout
34. // a 3 * 3 grid is created with the horizontal gap 20
35. // and vertical gap 25
36. frameObj.setLayout(new GridLayout(3, 3, 20, 25));
37. frameObj.setSize(300, 300);
38. frameObj.setVisible(true);
39. }
40. // main method
41. public static void main(String argvs[])
42. {
43. new GridLayoutExample();
44. }
45. }
Output:

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
Example of FlowLayout class: Using FlowLayout() constructor
FileName: FlowLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. FlowLayoutExample()
12. {
13. // creating a frame object
14. frameObj = new JFrame();
15.
16. // creating the buttons
17. JButton b1 = new JButton("1");
18. JButton b2 = new JButton("2");
19. JButton b3 = new JButton("3");
20. JButton b4 = new JButton("4");
21. JButton b5 = new JButton("5");
22. JButton b6 = new JButton("6");
23. JButton b7 = new JButton("7");
24. JButton b8 = new JButton("8");
25. JButton b9 = new JButton("9");
26. JButton b10 = new JButton("10");
27.
28.
29. // adding the buttons to frame
30. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameO
bj.add(b4);
31. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frame
Obj.add(b8);
32. frameObj.add(b9); frameObj.add(b10);
33.
34. // parameter less constructor is used
35. // therefore, alignment is center
36. // horizontal as well as the vertical gap is 5 units.
37. frameObj.setLayout(new FlowLayout());
38.
39. frameObj.setSize(300, 300);
40. frameObj.setVisible(true);
41. }
42.
43. // main method
44. public static void main(String argvs[])
45. {
46. new FlowLayoutExample();
47. }
48. }
Output:
Example of FlowLayout class: Using FlowLayout(int align) constructor
FileName: MyFlowLayout.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. // adding buttons to the frame
16. f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);
17.
18. // setting flow layout of right alignment
19. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new MyFlowLayout();
26. }
27. }
Output:

Example of FlowLayout class: Using FlowLayout(int align, int hgap, int


vgap) constructor
FileName: FlowLayoutExample1.java
1. // import statement
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample1
6. {
7. JFrame frameObj;
8.
9. // constructor
10. FlowLayoutExample1()
11. {
12. // creating a frame object
13. frameObj = new JFrame();
14.
15. // creating the buttons
16. JButton b1 = new JButton("1");
17. JButton b2 = new JButton("2");
18. JButton b3 = new JButton("3");
19. JButton b4 = new JButton("4");
20. JButton b5 = new JButton("5");
21. JButton b6 = new JButton("6");
22. JButton b7 = new JButton("7");
23. JButton b8 = new JButton("8");
24. JButton b9 = new JButton("9");
25. JButton b10 = new JButton("10");
26.
27.
28. // adding the buttons to frame
29. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameO
bj.add(b4);
30. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frame
Obj.add(b8);
31. frameObj.add(b9); frameObj.add(b10);
32.
33. // parameterized constructor is used
34. // where alignment is left
35. // horizontal gap is 20 units and vertical gap is 25 units.
36. frameObj.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));

37. frameObj.setSize(300, 300);


38. frameObj.setVisible(true);
39. }
40. // main method
41. public static void main(String argvs[])
42. {
43. new FlowLayoutExample1();
44. }
45. }
Output:

Java JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
1. public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


Methods Description
void setText(String s) It is used to set specified text on button
It is used to return the text of the
String getText()
button.
It is used to enable or disable the
void setEnabled(boolean b)
button.
It is used to set the specified Icon on the
void setIcon(Icon b)
button.
Icon getIcon() It is used to get the Icon of the button.
It is used to set the mnemonic on the
void setMnemonic(int a)
button.
void addActionListener(ActionListener It is used to add the action listener to
a) this object.
Java JButton Example
1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }
Output:

Java JButton Example with ActionListener


1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. }
Output:

Example of displaying image on the button:


1. import javax.swing.*;
2. public class ButtonExample{
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton(new ImageIcon("D:\\icon.png"));
6. b.setBounds(100,100,100, 40);
7. f.add(b);
8. f.setSize(300,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12. }
13. public static void main(String[] args) {
14. new ButtonExample();
15. }
16. }
Output:

what are the commonly used methods, and constructors and write sample code
of the following Swing components?
 JLabel  JTable
 JTextField  JList
 JTextArea  JOptionPane
 JPasswordField  JColorChooser
 JCheckBox  JDialog
 JRadioButton  JMenuItem & JMenu
 JComboBox

JButton
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener It is used to add the action listener to this object.
a)

JLabel
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty
string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.

JTextField
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and columns.
columns)
JTextField(int columns) Creates a new empty TextField with the specified number of columns.

Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive
action events from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener It is used to remove the specified action listener so that
l) it no longer receives action events from this textfield.

JCheckBox
Constructor Description
JCheckBox() Creates an initially unselected check box button with no
text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it
selected) is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.

Methods Description
AccessibleContext It is used to get the AccessibleContext associated with
getAccessibleContext() this JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.

JRadioButton

Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.

Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener It is used to add the action listener to this object.
a)

JComboBox
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified
array.
JComboBox(Vector<?> Creates a JComboBox that contains the elements in the specified
items) Vector.

Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is
editable.
void addActionListener(ActionListener It is used to add the ActionListener.
a)
void addItemListener(ItemListener i) It is used to add the ItemListener.

JTable

Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified data.
columns)

JList
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-
dataModel) null, model.

Methods Description
Void addListSelectionListener It is used to add a listener to the list, to be notified
(ListSelectionListener listener) each time a change to the selection occurs.
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from an
array of objects.

JPanel
Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.
JPanel(boolean It is used to create a new JPanel with FlowLayout and the
isDoubleBuffered) specified buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.

JFrame
Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank
title.
JFrame(String title) It creates a new, initially invisible Frame with the
specified title.
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.

Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by default
false.

JPasswordField

Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default document,
null starting text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the specified
number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the specified
text.
JPasswordField(String text, int Construct a new JPasswordField initialized with the specified
columns) text and columns.

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEven MouseWheelListener
t
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
 Button
o public void addActionListener(ActionListener a){}
 MenuItem
o public void addActionListener(ActionListener a){}
 TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
 TextArea
o public void addTextListener(TextListener a){}
 Checkbox
o public void addItemListener(ItemListener a){}
 Choice
o public void addItemListener(ItemListener a){}
 List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Java Event Handling Code
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Java event handling by implementing ActionListener
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been
used in the above example that sets the position of the component it may be
button, textfield etc.
2) Java event handling by outer class
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(tf);
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
23. }
1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }
3) Java event handling by anonymous class
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }

Java ActionListener Interface


The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent. The ActionListener interface is found in
java.awt.event package. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on
the registered component.
1. public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement
the ActionListener class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
1. public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
1. component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
1. public void actionPerformed(ActionEvent e){
2. //Write the code here
3. }
Java ActionListener Example: On Button click
1. import java.awt.*;
2. import java.awt.event.*;
3. //1st step
4. public class ActionListenerExample implements ActionListener{
5. public static void main(String[] args) {
6. Frame f=new Frame("ActionListener Example");
7. final TextField tf=new TextField();
8. tf.setBounds(50,50, 150,20);
9. Button b=new Button("Click Here");
10. b.setBounds(50,100,60,30);
11. //2nd step
12. b.addActionListener(this);
13. f.add(b);f.add(tf);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. //3rd step
19. public void actionPerformed(ActionEvent e){
20. tf.setText("Welcome to Javatpoint.");
21. }
22. }
Output:

Java ActionListener Example:


Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It
is notified against MouseEvent. The MouseListener interface is found in
java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Java MouseListener Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseLi
stener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }
Output:
Java MouseListener Example 2
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample2 extends Frame implements MouseL
istener{
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
16. public void mouseEntered(MouseEvent e) {}
17. public void mouseExited(MouseEvent e) {}
18. public void mousePressed(MouseEvent e) {}
19. public void mouseReleased(MouseEvent e) {}
20.
21. public static void main(String[] args) {
22. new MouseListenerExample2();
23. }
24. }
Output:
Java ItemListener Interface
The Java ItemListener is notified whenever you click on the checkbox. It is
notified against ItemEvent. The ItemListener interface is found in
java.awt.event package. It has only one method: itemStateChanged().
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or
unclick on the registered checkbox component.
1. public abstract void itemStateChanged(ItemEvent e);
Java ItemListener Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ItemListenerExample implements ItemListener{
4. Checkbox checkBox1,checkBox2;
5. Label label;
6. ItemListenerExample(){
7. Frame f= new Frame("CheckBox Example");
8. label = new Label();
9. label.setAlignment(Label.CENTER);
10. label.setSize(400,100);
11. checkBox1 = new Checkbox("C++");
12. checkBox1.setBounds(100,100, 50,50);
13. checkBox2 = new Checkbox("Java");
14. checkBox2.setBounds(100,150, 50,50);
15. f.add(checkBox1); f.add(checkBox2); f.add(label);
16. checkBox1.addItemListener(this);
17. checkBox2.addItemListener(this);
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public void itemStateChanged(ItemEvent e) {
23. if(e.getSource()==checkBox1)
24. label.setText("C++ Checkbox: "
25. + (e.getStateChange()==1?"checked":"unchecked"));
26. if(e.getSource()==checkBox2)
27. label.setText("Java Checkbox: "
28. + (e.getStateChange()==1?"checked":"unchecked"));
29. }
30. public static void main(String args[])
31. {
32. new ItemListenerExample();
33. }
34. }
Output:
Java WindowListener Interface
The Java WindowListener is notified whenever you change the state of window.
It is notified against WindowEvent. The WindowListener interface is found in
java.awt.event package. It has three methods.
WindowListener interface declaration
The declaration for java.awt.event.WindowListener interface is shown below:
1. public interface WindowListener extends EventListener
Methods of WindowListener interface
The signature of 7 methods found in WindowListener interface with their usage
are given below:
Sr. Method signature Description
no.
1. public abstract void It is called when the Window is set to
windowActivated (WindowEvent be an active Window.
e);
2. public abstract void It is called when a window has been
windowClosed (WindowEvent closed as the result of calling dispose
e); on the window.
3. public abstract void It is called when the user attempts to
windowClosing (WindowEvent close the window from the system
e); menu of the window.
4. public abstract void It is called when a Window is not an
windowDeactivated active Window anymore.
(WindowEvent e);
5. public abstract void It is called when a window is changed
windowDeiconified from a minimized to a normal state.
(WindowEvent e);
6. public abstract void It is called when a window is changed
windowIconified (WindowEvent from a normal to a minimized state.
e);
7. public abstract void It is called when window is made
windowOpened (WindowEvent visible for the first time.
e);
Methods inherited by the WindowListener
This interface inherits methods from the EventListener interface.
Working of WindowListener interface
 If a class needs to process some Window events, an object should exist
which can implement the interface.
 As the object is already registered with Listener, an event will be
generated on all the states of window.
 This helps in generation of invocation of relevant method in listener's
object. And then WindowEvent is passed after invocation.
Java WindowListener Example
In the following example, we are going to implement all the method of
WindowListener interface one by one.
WindowExample.java
1. // importing necessary libraries of awt
2. import java.awt.*;
3. import java.awt.event.WindowEvent;
4. import java.awt.event.WindowListener;
5.
6. // class which inherits Frame class and implements WindowListener int
erface
7. public class WindowExample extends Frame implements WindowListene
r{
8.
9. // class constructor
10. WindowExample() {
11.
12. // adding WindowListener to the frame
13. addWindowListener(this);
14. // setting the size, layout and visibility of frame
15. setSize (400, 400);
16. setLayout (null);
17. setVisible (true);
18. }
19. // main method
20. public static void main(String[] args) {
21. new WindowExample();
22. }
23.
24. // overriding windowActivated() method of WindowListener interfa
ce which prints the given string when window is set to be active
25. public void windowActivated (WindowEvent arg0) {
26. System.out.println("activated");
27. }
28.
29. // overriding windowClosed() method of WindowListener interface
which prints the given string when window is closed
30. public void windowClosed (WindowEvent arg0) {
31. System.out.println("closed");
32. }
33.
34. // overriding windowClosing() method of WindowListener interface
which prints the given string when we attempt to close window from syst
em menu
35. public void windowClosing (WindowEvent arg0) {
36. System.out.println("closing");
37. dispose();
38. }
39.
40. // overriding windowDeactivated() method of WindowListener inter
face which prints the given string when window is not active
41. public void windowDeactivated (WindowEvent arg0) {
42. System.out.println("deactivated");
43. }
44.
45. // overriding windowDeiconified() method of WindowListener interf
ace which prints the given string when window is modified from minimiz
ed to normal state
46. public void windowDeiconified (WindowEvent arg0) {
47. System.out.println("deiconified");
48. }
49.
50. // overriding windowIconified() method of WindowListener interfac
e which prints the given string when window is modified from normal to
minimized state
51. public void windowIconified(WindowEvent arg0) {
52. System.out.println("iconified");
53. }
54.
55. // overriding windowOpened() method of WindowListener interface
which prints the given string when window is first opened
56. public void windowOpened(WindowEvent arg0) {
57. System.out.println("opened");
58. }
59. }
Output:

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It
is notified against KeyEvent. The KeyListener interface is found in
java.awt.event package, and it has three methods.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
1. public interface KeyListener extends EventListener
Methods of KeyListener interface
The signature of 3 methods found in KeyListener interface are given below:
Sr.
Method name Description
no.
public abstract void keyPressed It is invoked when a key has been
1.
(KeyEvent e); pressed.
public abstract void keyReleased It is invoked when a key has been
2.
(KeyEvent e); released.
public abstract void keyTyped It is invoked when a key has been
3.
(KeyEvent e); typed.
Methods inherited
This interface inherits methods from the following interface:
 java.awt.EventListener
Java KeyListener Example
In the following example, we are implementing the methods of the KeyListener
interface.
KeyListenerExample.java
1. // importing awt libraries
2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits Frame class and implements KeyListener interfac
e
5. public class KeyListenerExample extends Frame implements KeyListener
{
6. // creating object of Label class and TextArea class
7. Label l;
8. TextArea area;
9. // class constructor
10. KeyListenerExample() {
11. // creating the label
12. l = new Label();
13. // setting the location of the label in frame
14. l.setBounds (20, 50, 100, 20);
15. // creating the text area
16. area = new TextArea();
17. // setting the location of text area
18. area.setBounds (20, 80, 300, 300);
19. // adding the KeyListener to the text area
20. area.addKeyListener(this);
21. // adding the label and text area to the frame
22. add(l);
23. add(area);
24. // setting the size, layout and visibility of frame
25. setSize (400, 400);
26. setLayout (null);
27. setVisible (true);
28. }
29. // overriding the keyPressed() method of KeyListener interface whe
re we set the text of the label when key is pressed
30. public void keyPressed (KeyEvent e) {
31. l.setText ("Key Pressed");
32. }
33. // overriding the keyReleased() method of KeyListener interface wh
ere we set the text of the label when key is released
34. public void keyReleased (KeyEvent e) {
35. l.setText ("Key Released");
36. }
37. // overriding the keyTyped() method of KeyListener interface wher
e we set the text of the label when a key is typed
38. public void keyTyped (KeyEvent e) {
39. l.setText ("Key Typed");
40. }
41. // main method
42. public static void main(String[] args) {
43. new KeyListenerExample();
44. }
45. }
Output:

Java KeyListener Example 2: Count Words & Characters


In the following example, we are printing the count of words and characters of
the string. Here, the string is fetched from the TextArea and uses the
KeyReleased() method of KeyListener interface.
KeyListenerExample2.java
1. // importing the necessary libraries
2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits Frame class and implements KeyListener interfac
e
5. public class KeyListenerExample2 extends Frame implements KeyListene
r{
6. // object of Label and TextArea
7. Label l;
8. TextArea area;
9. // class constructor
10. KeyListenerExample2() {
11. // creating the label
12. l = new Label();
13. // setting the location of label
14. l.setBounds (20, 50, 200, 20);
15. // creating the text area
16. area = new TextArea();
17. // setting location of text area
18. area.setBounds (20, 80, 300, 300);
19. // adding KeyListener to the text area
20. area.addKeyListener(this);
21. // adding label and text area to frame
22. add(l);
23. add(area);
24. // setting size, layout and visibility of frame
25. setSize (400, 400);
26. setLayout (null);
27. setVisible (true);
28. }
29. // even if we do not define the interface methods, we need to overr
ide them
30. public void keyPressed(KeyEvent e) {}
31. // overriding the keyReleased() method of KeyListener interface
32. public void keyReleased (KeyEvent e) {
33. // defining a string which is fetched by the getText() method of Te
xtArea class
34. String text = area.getText();
35. // splitting the string in words
36. String words[] = text.split ("\\s");
37. // printing the number of words and characters of the string
38. l.setText ("Words: " + words.length + " Characters:" + text.len
gth());
39. }
40. public void keyTyped(KeyEvent e) {}
41. // main method
42. public static void main(String[] args) {
43. new KeyListenerExample2();
44. }
45. }
Output:

You might also like