Example usage for javax.swing JFormattedTextField addCaretListener

List of usage examples for javax.swing JFormattedTextField addCaretListener

Introduction

In this page you can find the example usage for javax.swing JFormattedTextField addCaretListener.

Prototype

public void addCaretListener(CaretListener listener) 

Source Link

Document

Adds a caret listener for notification of any changes to the caret.

Usage

From source file:Main.java

public static void main(String... args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel contentPane = new JPanel();

    JFormattedTextField ftf = new JFormattedTextField(NumberFormat.getNumberInstance());
    ftf.setColumns(10);//www  .j a  v  a2 s. co m
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
    ftf.setValue(100);
    lastValidValue = "100";
    ftf.addCaretListener(e -> {
        System.out.println("Last Valid Value : " + lastValidValue);
        if (ftf.isEditValid()) {
            String latestValue = ftf.getText();
            System.out.println("Latest Value : " + latestValue);
            if (!(latestValue.equals(lastValidValue)))
                ftf.setBackground(Color.YELLOW.darker());
            else {
                lastValidValue = ftf.getText();
                ftf.setBackground(Color.WHITE);
            }
        } else {
            System.out.println("Invalid Edit Entered.");
        }
    });
    contentPane.add(ftf);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setVisible(true);
}