- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the importance of a FocusListener interface in Java?
FocusListener
- The focus events are generated whenever a component gains or loses the keyboard focus.
- The Objects representing focus events are created from FocusEvent Class.
- The corresponding listener interface for FocusEvent class is a FocusListener interface. Each listener for FocusEvent can implement the FocusListener interface.
- The FocusListener interface contains two methods focusGained(): Called by the AWT just after the listened-to component gets the focus and focusLost(): Called by the AWT just after the listened-to component loses the focus.
Syntax
public interface FocusListener extends EventListener { public void focusGained(FocusEvent fe); public void focusLost(FocusEvent fe);
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FocusListenerTest extends JPanel implements FocusListener { private JTextField textField; public FocusListenerTest() { setLayout(new BorderLayout()); textField = new JTextField(); textField.addFocusListener(this); add(textField, BorderLayout.NORTH); } public void focusGained(FocusEvent fe) { System.out.println("Text field gained focus"); } public void focusLost(FocusEvent fe) { System.out.println("Text field lost focus"); } public static void main(String args[]) { JFrame frame = new JFrame(); frame.add(new FocusListenerTest()); frame.setTitle("FocusListener Test"); frame.setSize(375, 250); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
Output
Advertisements
To Continue Learning Please Login
Login with Google