-1

I'm using Netbeans IDE I want to validate a text field that use to type the discount percentage. so that I want to stop typing numbers more than 100 in keytyped event.

Can anyone help me to solve this problem

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • check http://stackoverflow.com/questions/6172267/how-to-restrict-the-jtextfield-to-a-x-number-of-characters and http://stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters-in-jtextfield – Lakshmi Mar 21 '13 at 06:09
  • private void tcs_discountKeyTyped(java.awt.event.KeyEvent evt) { String A = tcs_discount.getText(); try{ int myint = Integer.ParseInt(A); if(!(myint >=0 && myint <= 100)) { evt.consume(); } } catch(Exception e) { } } – Hashain Lakshan Mar 21 '13 at 06:14
  • @HashainLakshan Don't, ever, use a `KeyListener` to try a filter a text component. You have no guarantee in the order that the `KeyListeners` or called and the key stroke may already have been sent to the field before you. They are also not called when the user pastes text into the field – MadProgrammer Mar 21 '13 at 06:28

1 Answers1

1

Don't use KeyListeners to try and filter text components.

Instead...

Updated with example

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestSpinner02 {

    public static void main(String[] args) {
        new TestSpinner02();
    }

    public TestSpinner02() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JSpinner spinner = new JSpinner();
                spinner.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(spinner);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366