yes, there's an area of Java I'm almost a complete novice in (so far, I'm going full steam ahead :cheesy: ).

I've the following code to filter out non-numeric input from a JTextField (which is meant to contain a timeout interval in minutes, that's why).

private void dumpNonNumericInput(KeyEvent e) {
        char input = e.getKeyChar();
        String oldText = ((JTextField)e.getSource()).getText();
        if (input != KeyEvent.VK_BACK_SPACE && input != KeyEvent.VK_DELETE &&
            (input < '0' || input > '9')) {
            JOptionPane.showMessageDialog(this, "Numeric input required",
                                          "Input error",
                                          JOptionPane.ERROR_MESSAGE);
            e.consume();
            ((JTextField)e.getSource()).setText(oldText);

        }
    }

This method works like a charm, that's not the problem.
The problem is that is I remove the error message popup (just the showMessageDialog command) the method no longer removes the faulty input either.
I THINK it's something to do with Swing thread timing, but I'm not sure.
Neither do I know how to cure this, which is more important at the moment as I'd rather not have that popup appear every time someone makes a typo.

I could probably subclass JTextField but that may be more trouble than it's worth.

A better alternative would be to disable text input altogether (call setEditable(false) on the text field. This deals with the problem of people putting in garbage input. Then all you need to do is use regular expression on the character that was input. Then use reg exp for input
if(stringvar.matches("\\d")){}

Not sure why removing a showMessageDialog would have any effect on the following code.

hi jwenting,

I have attached a Textfield which takes number of columns(maximum number of characters that the textfield can take) as parameter. If you use the usual textfields with keylistener, you can set illegal characters programattically. This textfield(one attached) does not allow illegal characters either by entry or progammatically. You can run the program attached and check out and tell me whether it was useful.

TextFieldDemo is the one with main method.

I am not sure whether this is exactly your requirement

regards
Srinivas

Attachments
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;

public class NumericTextField extends JTextField
{

  private final int MAX_CHARS_ALLOWED;
  int cols;
  	public NumericTextField()
  	{
  	MAX_CHARS_ALLOWED=0;
  	}

	//use this constructor if you want to control the maximum number of characters
  	public NumericTextField(int cols)
  	{
    	super(cols);
    	this.cols=cols;
    	this.MAX_CHARS_ALLOWED=cols;
  	}

  	protected Document createDefaultModel()
  	{
    	return new UpperCaseDocument(MAX_CHARS_ALLOWED);
  	}

  	class UpperCaseDocument extends PlainDocument
 	{

		private UpperCaseDocument(int MAX_CHARS_ALLOWED) 
		{
      			this.MAX_CHARS_ALLOWED = MAX_CHARS_ALLOWED;
    	}

    		final int MAX_CHARS_ALLOWED;

    		public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    		{
      			if(str==null)
      			{
      				return;
      			}
      			String s=NumericTextField.this.getText();
      			if(s.length()>=cols)
      			{
	  			selectAll();
				return;
      			}
		
      		char[] upper = str.toCharArray();

      			for(int i=0;i<upper.length;i++)
      			{
					//this will make sure that the entered characters are only numeric.
					//you can indicate the <optional> message by giving a * or any other symbol
					if((upper[i]>='0'&&upper[i]<='9'))
					{
		  				upper[i]=Character.toUpperCase(upper[i]);
					}
					else
					{
						JOptionPane.showMessageDialog(NumericTextField.this, "Numeric input required","Input error",JOptionPane.ERROR_MESSAGE);
		  				return;
					}
      			}
			super.insertString(offs, new String(upper), a);
 	 	}
	}
}
import javax.swing.*;
import java.awt.*;
class TextFieldDemo extends JFrame
{
	TextFieldDemo()
	{
		setSize(300,300);
		setLayout(new FlowLayout());
		add(new NumericTextField(10));
		show();
	}
	public static void main(String args[])
	{
		new TextFieldDemo();
	}
}

Cheers, I'll give it a look.

Gink, the idea is to allow only certain input. If it were readonly I'd have used a label or something else instead :)

Im not suggesting to make it read-only. What im saying is add a keylistener and whenever the user presses a key just update the textfield accordingly. The only reason I said uneditable is to prevent people from typing in characters that the keylistener doesnt respond to. It is still editable by the program, and the user wont know it's uneditable.

ah.

Found I can't catch shortcut keys (like Alt-T, Alt-X, etc.) using this system so I abandoned it.
Instead I now validate the field when it's value is read out instead of when it's input and give an error then.

Why not a boolean check method?

public boolean check(String text)
{
   try
   {
        Double.parseDouble(text);
        return true;
   }
   catch
   {
       JOptionPane.showMessageDialog(null,"Numeric crap only");
       return false;
   }
   return false;
}

yes, something like that :)
Thought to be a tad more friendly with my users though :p

try {
            Integer.parseInt(timeout.getText());
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this,
                                          "Timeout interval must be a number",
                                          "Input error",
                                          JOptionPane.ERROR_MESSAGE);
            return;
        }
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Inp extends JFrame{
    
    JPanel panel;
    JTextField field;
    Container container;
    InpKeyHandler handler;

    public Inp(){
        panel = new JPanel();
        field = new JTextField();
        field.setBackground(Color.WHITE);
        field.setHorizontalAlignment(JTextField.RIGHT);
        
        handler = new InpKeyHandler();
        
        container = getContentPane();
        container.setLayout(new BorderLayout());        
        field.addKeyListener(handler);
        
        
        field.setText("");
        field.setEditable(false);
        container.add(field,BorderLayout.NORTH);
        setSize(500,500);
        setVisible(true);
        
    }
    
    
    public static void main(String args[]){
        Inp in = new Inp();
        in.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    }
 
    public class InpKeyHandler extends KeyAdapter{
        String keyTyped;
        public void keyTyped(KeyEvent event){
          
          if((""+(event.getKeyChar())).matches("\\d")){
            keyTyped = field.getText();
            keyTyped += event.getKeyChar();
            field.setText(keyTyped);
          }
         }
            
    }
}

What do you mean your users? Are you teaching a class or something? Will however see the code?

I'm working on my SCJD exam. That means an examiner from Sun will see the code (and run it), and I hope some colleagues as friends as well if I can find people to test it first :)

And of course I work in the business, I doubt our customers would like such messages :eek:

will keep it in mind.
Got the first draft of the network server done, now working on the client application, and then to glue them together :)

yes, that's the idea :)
SCJP consists of learning a lot of stuff by rote and answering 60something multiple choice questions (with a rather low passing score).
SCJD consists of creating a complete client/server application from scratch including the database server and all documentation without using anything that's not part of the JDK itself (so no 3rd party or even optional Sun libraries, and some standard libraries are also not allowed, for example JDBC is explicitly disallowed).

yes, that's the idea :)
SCJP consists of learning a lot of stuff by rote and answering 60something multiple choice questions (with a rather low passing score).
SCJD consists of creating a complete client/server application from scratch including the database server and all documentation without using anything that's not part of the JDK itself (so no 3rd party or even optional Sun libraries, and some standard libraries are also not allowed, for example JDBC is explicitly disallowed).

pffsshhhhh, easy. :lol: :lol:

Just joking, let me know how do on it.

This article has been dead for over six months. Start a new discussion instead.