-1

I'm making a small app where I have two text fields. But I want it to be that when the user insert something that is not a number, it gives an alert message. I have done it like below but it does not work. I have tried tp use try & catch. Can anyone help me with this?

public void actionPerformed(ActionEvent ngjarja)
{
    String rresht = teksti1.getText(); 
    int rreshtii = Integer.parseInt(rresht);//kthimi i stringut ne integer
    String shtyll = teksti2.getText();
    int shtylle = Integer.parseInt(shtyll);

    if (ngjarja.getSource()== mat)
    mbushMatricenString(rreshtii,shtylle);  //Thirr metoden  

    if (ngjarja.getSource()== buton1)
     mbushVektorinString1( rreshtii,shtylle);

    try { Integer.parseInt(teksti1.getText());
    Integer.parseInt(teksti2.getText());


    } catch (NumberFormatException e) {
        JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
    }


}  
Kad
  • 388
  • 3
  • 15
user3233650
  • 419
  • 1
  • 4
  • 9
  • how about using the search field at the upper trailing edge of this page? It's a question asked about a trizillion times already with millions of correct answers .. – kleopatra Jan 26 '14 at 12:18
  • possible duplicate of [Only allowing numbers and a symbol (-) to be typed into a JTextField](http://stackoverflow.com/questions/8017811/only-allowing-numbers-and-a-symbol-to-be-typed-into-a-jtextfield) – kleopatra Jan 26 '14 at 12:19

3 Answers3

2

The problem is ActionListener will only be called when the user "actions" the field (typically by pressing Enter)

You could...

Use a InputVerfier which allows you to verify the state of the field.

Take a look at Validting Input for more details...

You Could...

Use a DocumentFilter to actually prevent the user from entering anything you didn't want them to.

Take a look at Implementing a Document Filter and MDP's Weblog for examples...

You Could...

Use a JSpinner instead

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • But I want to have the JOption Pane when I click the button, so this is the case when an action is performed – user3233650 Jan 25 '14 at 21:43
  • 2
    Perhaps if you'd posted a runnable example, we would have reached this point faster. You could forego the need for the button by using an InputVerifier, bit of you're really against his idea, update your question to include a runnable example that demonstrates your problem – MadProgrammer Jan 25 '14 at 22:11
1

Have a look at this example this only accepts number from user and displayed appropriate error message in JOptionPane.

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class Test {

    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField jtf = new JTextField();
        //add filter to document
        ((AbstractDocument) jtf.getDocument()).setDocumentFilter(new MyDocumentFilter());

        frame.add(jtf);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class MyDocumentFilter extends DocumentFilter {

    @Override
    public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
        for (int n = string.length(); n > 0; n--) {//an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want
            char c = string.charAt(n - 1);//get a single character of the string
            System.out.println(c);
            if (Character.isDigit(c)) {//if its an alphabetic character or white space
                super.replace(fb, i, i1, String.valueOf(c), as);//allow update to take place for the given character
            } else {//it was not an alphabetic character or white space
                System.out.println("Not allowed");
                JOptionPane.showMessageDialog(null, "Only Numbers are allowed");
            }
        }
    }

    @Override
    public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
        super.remove(fb, i, i1);
    }

    @Override
    public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
        super.insertString(fb, i, string, as);

    }
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59
0

Use This:

public class CustomTextField extends JTextField implements KeyListener{

    public CustomTextField() {
        super();

        addKeyListener(this);
    }

    @Override
    public void keyPressed(KeyEvent arg0) {

    }

    @Override
    public void keyReleased(KeyEvent arg0) {

    }

    @Override
    public void keyTyped(KeyEvent event) {
        char c = event.getKeyChar();

        if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c== KeyEvent.VK_DELETE)) {
            event.consume();
        }
    }
}