• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 465
  • Last Modified:

input checking

i have a JTextField that should input only positive integer numbers. So the user shouldn't be allowed to type in anything other than digit chars '0'-'9'. How can i do that ?

1. adding an InputVerifier only restricts the focus (when the text is incorrect). the user can still press buttons or change the tabs of a tabbedpane, leaving an inccorect input in my textfield. so InputVerifier is nice, but not enough for me.

2. i can check the text of the field in a CaretListener, but i cannot change it (with tf.setText(..)) because I get an "attempt to mutate in notifier" exception

3. a KeyListener was my first thought. I can set the text of the tf inside it, but the listener is notified before the text is changed by the keypress (and i can't just remove the event if i don't like it)

hope this makes, sense. any ideeas ? anyone ?

thnaks

0
hapciu
Asked:
hapciu
2 Solutions
 
zzynxSoftware engineerCommented:
0
 
krakatoaCommented:
If the above posted link from CEHJ doesn't already cover this, you could use the consume() method of the key event to throw away input you do not want.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
krakatoaCommented:
Maybe you can find a use for this:

//.................................................................................................................
    public static class kA extends KeyAdapter {                   //inner class
        public kA() {

      
            super();
        }


public void keyTyped(KeyEvent e){

if((!(e.getKeyChar()>='0'&&e.getKeyChar()<='9'))&&e.getKeyChar()!=','){e.consume();}

}




public void keyPressed(KeyEvent e){



if(e.isControlDown()==true){e.consume();}

}

    }                                           //end inner class
//.................................................................................................................

0
 
CEHJCommented:
8-)
0
 
CEHJCommented:
Bear in mind that a KeyListener will not validate pasted input
0
 
krakatoaCommented:
>> Bear in mind that a KeyListener will not validate pasted input ...

Not /quite/ true. ;) It is true for a JTextField, but not (on my system at least) for a TextField, into which you cannot paste.

0
 
CEHJCommented:
>>TextField, into which you cannot paste.

?? A window you can't paste into - are you sure?
0
 
hapciuAuthor Commented:
now, boys, calm down :)

it's true you can paste into the text field (at least into my text field) but what i wanted was the KeyListener to block non-digit characters. and i got that. also, i was kinda dumb not to check the new JFormattedTexField so that was useful too.
0
 
CEHJCommented:
>>but what i wanted was the KeyListener to block non-digit characters.

The point is it *won't* if you paste them
0
 
CEHJCommented:
(btw i'm not complaining or getting at krakatoa - merely pointing out a fact ;-))
0
 
krakatoaCommented:
>> now, boys, calm down :)  ...

It's fine hapciu - we are only discussing the facts, and there's no friction - I wouldn't attempt to throw my weight around against CEHJ, don't worry. ;)

I am "sure" that CEHJ's, and zzynx's links for that matter, are pointing at more thoroughgoing solutions than mine; having said that, the only drawback to my code is the one referred to by CEHJ, which is the pasting issue. I have a test class in which I have a JTextField and a TextField, and according to how that works, I see that a right click, pop-up menu paste operation into a TextField is not possible, whilst that operation is possible on a JTextField. I therefore disabled the CTRL key to stop a CTRL-V pasting, and, AFAICS, this is about as near robust as that approach will allow.

Just for the hell of it I can post the messy code to show this (ignore the console output etc if you run it, it is a class that has been hacked around for testing several things). The upper field is the TextField, and the lower one is the JTextField. Don't ask me what the ABCDEF and the timezone stuff is for - I've forgotten! :))

0
 
krakatoaCommented:
TextField and JTextField behaviour comparison:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import java.util.TimerTask;
import java.util.Vector;


public class nums extends JFrame implements ActionListener, WindowListener{

private FileOutputStream fis;
private File datecheater;
private static java.awt.List lis;
private JTextField indices;
private TextField tf;
private JLabel indexesLabel;

private static TextField jtf;

protected kA keyadapter;
protected java.awt.datatransfer.Clipboard clip;

protected boolean running;
protected javax.swing.JRadioButton rb;

protected int[] pa;




public nums(){


//datecheater = new File("C:/gbjunk/datecheater.txt");
//byte[] b=new byte[1];
//b[0]=(byte)'b';
//try{
//fis = new FileOutputStream(datecheater);
//try{
//fis.write(b);
//datecheater.setLastModified(java.util.Calendar.getInstance().getTimeInMillis());
//}catch(IOException ioe){}
//}catch(FileNotFoundException fnf){}
//System.out.println(datecheater.lastModified());




lis = new java.awt.List();
lis.setSize(new Dimension(200,400));

jtf = new TextField("ABCDEFGH");
//jtf.setColumns(3);
Dimension d = jtf.getPreferredSize();
this.getContentPane().add(jtf);
//jtf.setText(jtf.getText().substring(0,4));
jtf.setSize(d.width/2,d.height/2);
jtf.repaint();

/*
try{
jtf.scrollRectToVisible(jtf.modelToView(0));
}catch(javax.swing.text.BadLocationException ble){}
*/




System.out.println(jtf.getText());
/*
THIS WORKS SO LEAVE IT IN FOR REFERENCE!
String[] sarr;
String str = "C:\\Documents and Settings\\peikfeng\\My Documents";
sarr=str.split("\\\\");


for(int a=0;a<sarr.length;a++){
System.out.println(sarr[a]);
}
*/

//THIS WORKS BUT DIDNT NEED IT SOMETIMES SO REMMED - CAN REM IT BACK IF YOU WANT
System.out.println(java.util.Calendar.getInstance().getTime());



System.out.println(System.currentTimeMillis()+" is the System Time");
System.out.println(System.currentTimeMillis()-java.util.Calendar.getInstance().getTimeInMillis());

java.util.Date date = new java.util.Date();
System.out.println(date.getTime()/1000/60/60/24);

System.out.println(java.util.TimeZone.getDefault().getDisplayName());


 try {
 String os=""+System.getProperties().get("os.name");
 if (os.equals("Windows 2000") || os.equals("Windows XP") || os.equals("Windows NT"))
{
System.out.println("W2000");
//Runtime.getRuntime().exec("cmd /c c:\\mysql\\bin\\mysql backuphotel < C:\\backup\\"+backfile+".sql");
}
else if (os.equals("Windows 95") || os.equals("Windows 98"))
{
System.out.println(os);
//Runtime.getRuntime().exec("C:\\command "+(char)34+"c:\\gbjunk\\filea.bat"+(char)34);
}
//JOptionPane.showMessageDialog(this, "File Successfully restored!");
} // end try
catch ( Exception e ) {
     //JOptionPane.showMessageDialog(this, "Restore failed!");        
}








keyadapter = new kA();
indexesLabel = new JLabel("Enter Some Data");
indices = new JTextField(50);
tf = new TextField(50);

rb = new javax.swing.JRadioButton();
pa = new int[2000000];


for(int a=1;a<pa.length+1;a++){pa[a-1]=a;}


System.out.println("pa[First] = "+pa[0]+ " pa[Last] = "+pa[1999999]);



indices.addKeyListener(keyadapter);
tf.addKeyListener(keyadapter);

this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.getContentPane().setLayout(new FlowLayout());
this.setSize(1000,400);

this.getContentPane().add(indexesLabel);
this.getContentPane().add(indices);
this.getContentPane().add(tf);

this.getContentPane().add(rb);

this.getContentPane().add(lis);

indices.addActionListener(this);
tf.addActionListener(this);

}//end constructor








public void windowClosing(WindowEvent w){

System.exit(0);

}//end windowclosing



public void windowIconified(WindowEvent w){}
public void windowDeiconified(WindowEvent w){}
public void windowMinimised(WindowEvent w){}
public void windowMaximized(WindowEvent w){}
public void windowClosed(WindowEvent w){}
public void windowOpened(WindowEvent w){}
public void windowActivated(WindowEvent w){}
public void windowDeactivated(WindowEvent w){}


public void actionPerformed(ActionEvent e){


if(e.getSource()==indices){

/*
java.awt.Toolkit tkit = java.awt.Toolkit.getDefaultToolkit();

clip = tkit.getSystemClipboard();

clip.setContents(null,null);
*/

}

indices.setText(" "+rb.isSelected());


}//end actionperformed










public static void main(String args[]){

new nums().show();
try{
String machineDetails = java.net.InetAddress.getLocalHost().toString();

String [] machineIDs = machineDetails.split("/");

System.out.println("The name of this machine is "+machineIDs[0]);
System.out.println("The IP of this machine is "+machineIDs[1]);
java.net.InetAddress[] inets;
java.net.InetAddress inet;

inets = java.net.InetAddress.getAllByName("localHost");
System.out.println(inets[0]);

inet = java.net.InetAddress.getByName("localHost");
System.out.println(inet);

String hosta = java.net.InetAddress.getLocalHost().getHostAddress();
System.out.println(hosta);


byte[] hoste = java.net.InetAddress.getLocalHost().getAddress();
for(int a=0;a<hoste.length;a++){
System.out.println((int)hoste[a]);
}
/*
try}
Socket isock = new Socket("localhost",30301);
java.net.InetAddress sockinet = isock.getLocalAddress();
System.out.println(sockinet.toString());
}catch(IOException hio){}
*/
try{
java.net.InetAddress i = new java.net.MulticastSocket(6789).getInterface();
System.out.println(i.toString());
}catch(IOException yu){}



}catch(UnknownHostException ukgb){}

System.out.println((char)163);
System.out.println((char)163);

System.out.println(java.util.Calendar.DST_OFFSET);
System.out.println(java.util.Calendar.ZONE_OFFSET);

if((!java.util.TimeZone.getDefault().useDaylightTime())&&(java.util.TimeZone.getDefault().inDaylightTime(new java.util.Date()))){

System.out.println("You need to add "+java.util.TimeZone.getDefault().getDSTSavings()/1000/60/60+" hours so that Java Time = System Time.");

}

System.out.println((java.util.TimeZone.getDefault()).inDaylightTime(new java.util.Date()));

String[] ids = java.util.TimeZone.getDefault().getAvailableIDs();
for(int a=0;a<ids.length;a++){
//System.out.println(ids[a]);
lis.add(ids[a]);
}


jtf.setCaretPosition(0);


}// end main



//.................................................................................................................
    public static class kA extends KeyAdapter {                   //inner class
        public kA() {

      
            super();
        }


public void keyTyped(KeyEvent e){

if((!(e.getKeyChar()>='0'&&e.getKeyChar()<='9'))&&e.getKeyChar()!=','){e.consume();}

}




public void keyPressed(KeyEvent e){



if(e.isControlDown()==true){e.consume();}

}

    }                                           //end inner class
//.................................................................................................................




}//end nums
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now