2

I'm new to java and I'm trying to make a simple program that will delete the user's input on a textfield if it is not an integer.

private void jTextField4KeyPressed(java.awt.event.KeyEvent evt) {   
    int j;
    try {
        j = Integer.parseInt(jTextField4.getText());
    }
    catch (NumberFormatException f) {
      jOptionPane1.showMessageDialog(null, "AwtsuPaytsu");
      jTextField4.setText("");
    }
}

It successfully deletes non-integer inputs automatically. However, it also deletes integer inputs. What should I do? I really need help. I want to learn.

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
user3260589
  • 168
  • 1
  • 4
  • 12

5 Answers5

2

Look at this example this will only accept numbers from user. Here I have used Document Filter to accept only numbers and not other.

import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
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 InputInteger
{
private JTextField tField;
private JLabel label=new JLabel();
private MyDocumentFilter documentFilter;

private void displayGUI()
{
    JFrame frame = new JFrame("Input Integer Example");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JPanel contentPane = new JPanel();
    contentPane.setBorder(
        BorderFactory.createEmptyBorder(5, 5, 5, 5));
    tField = new JTextField(10);
    ((AbstractDocument)tField.getDocument()).setDocumentFilter(
            new MyDocumentFilter());

    contentPane.add(tField); 
    contentPane.add(label);


    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}
public static void main(String[] args)
{
    Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
            new InputInteger().displayGUI();
        }
    };
    EventQueue.invokeLater(runnable);
}
}

class MyDocumentFilter extends DocumentFilter{
    private static final long serialVersionUID = 1L;
    @Override
public void insertString(FilterBypass fb, int off
                    , String str, AttributeSet attr) 
                            throws BadLocationException 
{
    // remove non-digits
    fb.insertString(off, str.replaceAll("\\D++", ""), attr);
} 
@Override
public void replace(FilterBypass fb, int off
        , int len, String str, AttributeSet attr) 
                        throws BadLocationException 
{
    // remove non-digits
    fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
}
}

Useful link

Implementing a Document Filter

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
  • This. I can't understand. – user3260589 Feb 01 '14 at 15:09
  • I'm just a beginner. Please put something that I can easily understand. – user3260589 Feb 01 '14 at 15:10
  • @user3260589 using keyListener on TextField is not a good practice, you have to go with the proper way, and proper way is to use the Document Listener. Just go thr' the link above or search for document listener on Google you will get it. – ravibagul91 Feb 01 '14 at 16:29
  • 1
    +1 for the documentFilter, -1 for still having a (unneeded) keyListener, zeroes out ;) – kleopatra Feb 02 '14 at 10:01
  • @user3260589 if you don't understand this simple example you might consider not coding at all .. anyway, there's no way around reading a decent textbook/tutorial to learn the basics - there's reference to a good online tutorial in the swing tag wiki – kleopatra Feb 02 '14 at 10:03
  • @kleopatra Here `keyListener` is just for setting the `label` value as we type in `jTextField`, one can remove it. Actually there is no need to use `keyListener` at all. – ravibagul91 Feb 02 '14 at 10:09
  • _Actually there is no need to use keyListener at all_ agreed. Hint: you can edit your answer, as you know :-) – kleopatra Feb 02 '14 at 10:14
0

So you want to remove all the non-digits from the string and set that again in text field. You can try the following.

private void jTextField4KeyPressed(java.awt.event.KeyEvent evt) {   
    String str = jTextField4.getText();
    StringBuilder str1 = new StringBuilder();

    for(int i = 0; i <= str.length() - 1; ++i) {

        if(!Character.isLetter(str.charAt(i))) {
            str1.append(str.charAt(i));
        }
            else {
                jOptionPane1.showMessageDialog(null, "AwtsuPaytsu");
            }

    }
    jTextField4.setText(str1);

}
udit bansal
  • 106
  • 3
0

Even if i think Jugadus approach here is the right one. (not enough rep for commenting sorry)

It seems to be quite a bit too much for the questioner.

In my opinion fixing it after it has been written is just a bad approach.

I think you should take a look at:

https://stackoverflow.com/a/11093360/661142

By using keyListeners you're missing quite a few things (like pasting etc)

or use a JFormattedTextField for that purpose like in:

https://stackoverflow.com/a/16228698/661142

Community
  • 1
  • 1
eiselems
  • 170
  • 1
  • 12
-1

From jTextField events, choose keyReleased event not keyPressed! And put this code inside the new generated handler:

private void keyReleased(java.awt.event.KeyEvent evt) {                             
    try {
        Integer.parseInt(jTextField2.getText());
    } catch (NumberFormatException f) {
        if (!jTextField2.getText().isEmpty())
            JOptionPane.showMessageDialog(null, "AwtsuPaytsu");
        jTextField2.setText(jTextField2.getText().replaceAll("[^0-9]", ""));
        //jTextField2.setText("");
    }
}

keyReleased event

-2

Try:

jTextField4.setText(jTextField4.getText().replaceAll("[^0-9]", ""));