Midoes
Midoes

Reputation: 89

How to validate only float numbers in a JFormattedText with Java Swing?

What is the best way to validate a float number using a JFormattedText or JTextField element?.

I don't want to validate trough an event like keypress or keydown, there is some JFormattedText method?.

Upvotes: 0

Views: 493

Answers (1)

markspace
markspace

Reputation: 11020

The semantics of a JFormattedTextField are a little weird, but they might work for you. The trick is to set the value of the formatted text field to an object that can be used as a formatter. Floats work just fine.

JFormattedTextField jff = new JFormattedTextField( 0.0f );

JFormattedTextFields won't stop the user from entering bad input though. They just revert to the old (correct) value if the user enters bad data. If you want different behavior you might have to do the key press thing, sometimes it's the only way.

public class Validation
{

   public static void main( String[] args )
   {
      SwingUtilities.invokeLater( new Runnable()
      {
         public void run()
         {
            JFrame frame = new JFrame();

            Box vbox = Box.createVerticalBox();

            JFormattedTextField jff = new JFormattedTextField( 0.0f );
            vbox.add(jff);
            JTextField jt = new JTextField( 20 );
            vbox.add( jt );
            JLabel value = new JLabel( jff.getValue().toString() );
            vbox.add( value );
            frame.add( vbox );
            JButton b = new JButton( "Get Value" );
            b.addActionListener( new ActionListener()
            {

               @Override
               public void actionPerformed( ActionEvent e )
               {
                  value.setText( jff.getValue().toString() );
               }
            } );
            JPanel p = new JPanel();
            p.add( b );
            frame.add( p, BorderLayout.SOUTH );

            frame.pack();
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setLocationRelativeTo( null );
            frame.setVisible( true );
         }
      } );
   }
}

Upvotes: 1

Related Questions