Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Color;
import java.text.NumberFormat;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    static String lastValidValue;

    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);
        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);
    }
}