Caret Event and Listener in Java

This tutorial will teach you how to create a program that will have an example of Caret Event and Listener in Java. A CaretEvent lets the user notify interested parties that the text caret has changed in the event with its source. Note: A caret is the cursor indicating the insertion point So, now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of caretListener.java. 2. Import the swing package library:
  1. import javax.swing.*; //used to access the JFrame,JScrollPane, and JTextArea
  2. import javax.swing.event.*; //used to access CaretEvent and CaretListener
3. We will initialize variables in our Main, variable frame as JFrame and txtArea as JTextArea.
  1. JFrame frame = new JFrame();
  2. JTextArea txtArea = new JTextArea();
  3.  
4. Now, we will add the CaretListener to the txtArea.
  1.  
  2. txtArea.addCaretListener(new CaretListener() {
  3. public void caretUpdate(CaretEvent e) {
  4. System.out.println(e);
  5.  
  6. }
  7. });
As what have you seen in the code above, a caret changes its position or if text is selected, a caret event is fired by the textArea. The class CaretEvent supports the methods getDot() and getMark() to retrieve the current location and the end position of a text selection. And it will display the console the dot and the mark position of the text. 5. Lastly, add the txtArea with its JScrollPane component, set the size, visibility, and the close operation of the frame. Have this code below:
  1. frame.getContentPane().add(new JScrollPane(txtArea));
  2.  
  3. frame.setSize(300, 200);
  4. frame.setVisible(true);
  5. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output: output Here's the full code of this tutorial:
  1. import javax.swing.*; //used to access the JFrame,JScrollPane, and JTextArea
  2. import javax.swing.event.*; //used to access CaretEvent and CaretListener
  3.  
  4. public class caretListener {
  5.  
  6. public static void main(String[] a) {
  7. JFrame frame = new JFrame();
  8. JTextArea txtArea = new JTextArea();
  9.  
  10.  
  11.  
  12. txtArea.addCaretListener(new CaretListener() {
  13. public void caretUpdate(CaretEvent e) {
  14. System.out.println(e);
  15.  
  16. }
  17. });
  18.  
  19. frame.getContentPane().add(new JScrollPane(txtArea));
  20.  
  21. frame.setSize(300, 200);
  22. frame.setVisible(true);
  23. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  24. }
  25.  
  26. }
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment