Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7825595
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T09:04:22+00:00 2026-06-02T09:04:22+00:00

For a task I need to make a JFormattedTextField with the following behavior: If

  • 0

For a task I need to make a JFormattedTextField with the following behavior:

  • If value is edited and isn’t equal to the last validated value the background must become yellow.
  • Value validation may take place at any time
  • If focus is lost nothing should happen (if background is yellow it should remain yellow,…)
  • Action should be taken when Enter is pressed

I can’t seem to find the correct combination of Listeners to accomplish this. I tried using KeyAdapter, InputVerifier and PropertyChangeListenerbut that gives me very ugly code wich only works for 80%.

How should this be done?

Edit: I wrote a small example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.ParseException;

import javax.swing.AbstractAction;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test extends JPanel {

    private JFormattedTextField field;
    private JLabel label;
    private JButton btn;

    public Test() {
        super(new BorderLayout());

        label = new JLabel("Enter a float value:");
        btn = new JButton(new AbstractAction("Print to stdout"){

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(field.getValue());
            }

        });
        field = new JFormattedTextField(new Float(9.81));

        field.addKeyListener(new KeyAdapter(){

            @Override
            public void keyPressed(KeyEvent e){
                field.setBackground(Color.YELLOW);
            }

            @Override 
            public void keyTyped(KeyEvent e){
                if(e.getKeyCode() == KeyEvent.VK_ENTER){
                    try{
                        field.commitEdit();
                        field.setBackground(Color.WHITE);
                    }catch(ParseException e1){
                        field.setBackground(Color.RED);
                    }
                }
            }
        });

        field.setInputVerifier(new InputVerifier(){

            @Override
            public boolean verify(JComponent comp) {
                try{
                    field.commitEdit();
                    field.setBackground(Color.YELLOW);
                    return true;
                }catch(ParseException e){
                    field.setBackground(Color.RED);
                    return false;
                }
            }

        });

        add(label, BorderLayout.NORTH);
        add(field, BorderLayout.CENTER);
        add(btn, BorderLayout.SOUTH);
    }


    public static void main(String[] args) {
        JFrame window = new JFrame("InputVerifier test program");
        Container cp = window.getContentPane();
        cp.add(new Test());
        window.pack();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
    }
}

This almost does everything I want. But the problem is the ENTER key is never caught. I think it is consumed before it reaches my KeyListener, but how can I prevent this?

Even if this can be prevented, I still have the feeling there should be a cleaner why to accomplish what above code does.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T09:04:24+00:00Added an answer on June 2, 2026 at 9:04 am

    Try your hands on this code sample, tell me is this the desired behaviour, or you expecting something else, other than this :

    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    
    public class JFormattedExample
    {
        private String lastValidValue;
    
        private void createAndDisplayGUI()
        {
            JFrame frame = new JFrame("JFormattedTextField Example");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
            JPanel contentPane = new JPanel();
            contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    
            final JFormattedTextField ftf = new JFormattedTextField(
                                NumberFormat.getNumberInstance());
            ftf.setColumns(10);
            ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
            ftf.setValue(100);
            lastValidValue = "100";
            ftf.addCaretListener(new CaretListener()
            {
                public void caretUpdate(CaretEvent ce)
                {
                    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.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String... args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new JFormattedExample().createAndDisplayGUI();
                }
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to make a long running task in the background. I'm using OmniThreadLibrary
I need to make next task: file: string1 data1 data I need to create
I'm scratching my head on how to accomplish the following task: I need to
I have a task I need to perform, do_stuff(opts) , that will take ~1s
I have a rake task I need to run as a daily job on
I have a jQuery function already to perform the task I need but is
I have a task where I need to translate a DataTable to a two-dimensional
I have a task where i need to write a multidimensional array to HDFS.
I'm newbie for python, I'm having task so I need to scan wifi and
I need to run a task in CruiseControl .NET before checking for modification in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.