Java Tutorial/Swing Event/CaretListener
Caret Events and Listeners
Whenever a caret changes its position or if text is selected, a caret event is fired by a text component. The class CaretEvent supports the methods getDot() and getMark() to retrieve the current location and the end position of a text selection, respectively.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class CaretEeventListener {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent e) {
System.out.println(e);
}
});
frame.add(new JScrollPane(textField));
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Listen to CaretEvent with CaretListener
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Main implements ActionListener {
JTextField jtf = new JTextField(10);
JButton jbtnGetTextUpper = new JButton("Get Text In Uppercase");
Main() {
JFrame jfrm = new JFrame("Demonstrate a Text Field");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(240, 140);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.setActionCommand("TF");
jtf.addActionListener(this);
jbtnGetTextUpper.addActionListener(this);
jtf.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
System.out.println("Text in real time: " + jtf.getText());
}
});
jfrm.add(jtf);
jfrm.add(jbtnGetTextUpper);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("TF")) {
System.out.println("ENTER key pressed: " + jtf.getText());
} else {
String str = jtf.getText().toUpperCase();
System.out.println("Button pressed: " + str);
}
}
public static void main(String args[]) {
new Main();
}
}