Focus Event in Java with Examples

explore java logo

Table of Contents

a) Introduction
b) Different Method of Focus Event
c) Example with Source code
d) Output

*********************

Introduction

Focus Event is the low-level event which indicates the focus gained or focus lost from the keyboard. It is generated by the components such as text field. The event generated is passed through every FocusListener or FocusAdapter objects which is registered by addFocusListener to receive the event.

The methods of the Focus Event are:

public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)

Let us see the example of Focus Event using FocusListener;

To use the FocusListener interface we have to implement it to the main class as shown in below code.

Source Code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package EventHandling;

/**
 *
 * @author AnkitPC
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FocusEventDemo implements FocusListener{
    JFrame f1;
    JTextField t1, t2;
    FocusEventDemo(){
        f1= new JFrame();
        f1.setSize(300, 300); //size of frame
        f1.setLayout(new FlowLayout()); //setting layout
       
        f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
       
        t1= new JTextField(20);
        t2= new JTextField(20);
        //adding component to the frame
        f1.add(t1);
        f1.add(t2);
        //registering the event
        t1.addFocusListener(this);
        t2.addFocusListener(this);
       
        f1.setVisible(true);
    }
    public static void main(String[] args) {
        new FocusEventDemo(); //calling constructor
    }
   
    public void focusGained(FocusEvent e){
        if(e.getSource()==t1){
            t1.setBackground(Color.cyan);
        }
        else if(e.getSource()==t2){
            t2.setBackground(Color.cyan);
        }
    }
    public void focusLost(FocusEvent e){
        if(e.getSource()==t1){
            t1.setBackground(Color.red);
        }
        else if(e.getSource()==t2){
            t2.setBackground(Color.red);
        }
    }
}

If we use Listener interface than we have to override the all methods that is in Focus Listener. As you can see that there are only two methods of focus event so we override both. In the source code you can see that when focus is gained then it shows the color cyan and if focus is lost then it shows the color red.

Output:
focus event explore java

In this figure above, focus is gained by the text field first and focus is lost in text field second.

focus event explore java

Now in the figure above you can see the focus is gained by the second text field and lost by first text field.

Also let us see the example of Focus Event using FocusAdpater;

To use FocusAdapter we extend the Adapter class to the main class as shown in the code below.

Source Code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package EventHandling;

/**
 *
 * @author AnkitPC
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FocusEventDemo extends FocusAdapter{
    JFrame f1;
    JTextField t1, t2;
    FocusEventDemo(){
        f1= new JFrame();
        f1.setSize(300, 300); //size of frame
        f1.setLayout(new FlowLayout()); //setting layout
       
        f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
       
        t1= new JTextField(20);
        t2= new JTextField(20);
        //adding component to the frame
        f1.add(t1);
        f1.add(t2);
        //registering the event
        t1.addFocusListener(this);
        t2.addFocusListener(this);
       
        f1.setVisible(true);
    }
    public static void main(String[] args) {
        new FocusEventDemo(); //calling constructor
    }
   
    public void focusGained(FocusEvent e){
        if(e.getSource()==t1){
            t1.setBackground(Color.cyan);
        }
        else if(e.getSource()==t2){
            t2.setBackground(Color.cyan);
        }
    }
   
}

Now in the source code above you can see that I have removed the focusLost method. But also the code is working, So the main reason of using the Adapter class over Listener interface is that we can override the method which is required.

Output:


focus event explore java

In the above code i have removed the method focusLost so it only shows the focus gained by the textfield.

focus event explore java


Key Event in Java with Examples

Table of Contents

a) Introduction to Key Event
b) Different types of methods of Key Event
c) Example with Source Code
d) Output

****************

Introduction

Key Event is generates if and only if the state of the key is changed. It is generated by the components such as text field. The event generated is passed through every KeyListener or KeyAdapter objects which is registered by addKeyListener to receive the event. The interface KeyListener and class KeyAdapter is found in java.awt.event package.

Key Event has three methods, they are;

a) public void keyPressed(KeyEvent e)
b) public void keyReleased(KeyEvent e)
c) public void keyTyped(KeyEvent e)

Let us see the example of Key Event using KeyListener interface;

To use key listener interface we should implement it to the main class as shown in the code.

Source Code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package EventHandling;

/**
 *
 * @author AnkitPC
 */

import javax.swing.*; //for components
import java.awt.*; //for layout
import java.awt.event.*; //for event handling
public class KeyEventDemo implements KeyListener{
    JFrame f1;
    JLabel l1, l2,l3;
    JTextField t1, t2;
   
    KeyEventDemo(){ //constructor
        f1= new JFrame();
        f1.setSize(300, 300);
        f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f1.setLayout(new FlowLayout());
      //creating a object 
        l1= new JLabel("Name");
        l2= new JLabel("Contact");
       
        t1= new JTextField(20);
        t2= new JTextField(20);
       
        l3=new JLabel("Status");
      //adding the components to the frame 
        f1.add(l1);
        f1.add(t1);
        f1.add(l2);
        f1.add(t2);
        f1.add(l3);
//registering the event
        t1.addKeyListener(this);
        t2.addKeyListener(this);
       
        f1.setVisible(true);
    }
   //main method
    public static void main(String[] args) {
        //calling the constructor
        new KeyEventDemo();
    }
    public void keyPressed(KeyEvent e){
        l3.setText("Key Pressed");
    }
    public void keyReleased(KeyEvent e){
        l3.setText("Key Released");
    }
   
    public void keyTyped(KeyEvent e){
        char ch= e.getKeyChar();       
        if(e.getSource()==t1){
            if(!(ch>='a' && ch<='z' || ch>='A' && ch<='Z')){
                e.consume();
            }
        }
        else if(e.getSource()==t2){
            String s= t2.getText();
            int len= s.length();
            if(len>=10){
                e.consume();
            }
            if(!(ch>='0' && ch<='9')){
                e.consume();
            }
        }
    }
}

Output:
The first image is the initial output if you run the program.
keyevent explore java


If you press any key in the name field then it will only take the a-z character but not numbers. The screen shot of the key pressed is done by pressing the shift key.


keyevent explore java

In the contact field, you can only type the numbers not characters. As shown in the figure.

keyevent explore java

Now let us see the example of the key event using key adapter;

To use the adapter class, we should extends to the main class as shown in code below.

Source Code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package EventHandling;

/**
 *
 * @author AnkitPC
 */

import javax.swing.*; //for components
import java.awt.*; //for layout
import java.awt.event.*; //for event handling
public class KeyEventDemo extends KeyAdapter{
    JFrame f1;
    JLabel l1, l2;
    JTextField t1, t2;
   
    KeyEventDemo(){ //constructor
        f1= new JFrame();
        f1.setSize(300, 300);
        f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f1.setLayout(new FlowLayout());
      //creating a object 
        l1= new JLabel("Name");
        l2= new JLabel("Contact");
       
        t1= new JTextField(20);
        t2= new JTextField(20);
       
     
      //adding the components to the frame 
        f1.add(l1);
        f1.add(t1);
        f1.add(l2);
        f1.add(t2);
       
//registering the event
        t1.addKeyListener(this);
        t2.addKeyListener(this);
       
        f1.setVisible(true);
    }
   //main method
    public static void main(String[] args) {
        //calling the constructor
        new KeyEventDemo();
    }

    public void keyTyped(KeyEvent e){
        char ch= e.getKeyChar();       
        if(e.getSource()==t1){
            if(!(ch>='a' && ch<='z' || ch>='A' && ch<='Z')){
                e.consume();
            }
        }
        else if(e.getSource()==t2){
            String s= t2.getText();
            int len= s.length();
            if(len>=10){
                e.consume();
            }
            if(!(ch>='0' && ch<='9')){
                e.consume();
            }
        }
    }
}

Output:

The first image is the initial output of the program. In this program I have removed the JLabel l3 and methods keyPressed() and keyReleased().

keyevent explore java

The name field only contains a-Z characters only and contact field only contains numbers. You can check it by using the source code above.

keyevent explore java