java character textfield validation - java

I want name textfield validation and I am using this code, what is not working perfectly.
Name_text.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent EVT){
if(EVT.getKeyChar()>='a'&& EVT.getKeyChar()<='z'|| EVT.getKeyChar()>='A'&& EVT.getKeyChar()<='Z'|| EVT.getKeyChar()==8|| EVT.getKeyChar()==26){
Name_text.setEditable(true);
}
else{
JOptionPane.showMessageDialog(null, "enter characters only");
}

You really should perform this type of validation using the DocumentFilter class, this is exactly what it's designed for. If the user pastes text into the field or you use setText, you will not be notified of the change via the KeyListener
You could also check out this for a number of examples

I guess you want to validate with this code :
if (Character.isDigit(EVT.getKeyChar())) {
Name_text.setEditable(true);
Name_text.setText("");
} else {
JOptionPane.showMessageDialog(null, "enter characters only");
}
Edited by your comment.

Related

How to make keyboard enter button say “Search” when any one type in browser other wise it used as Enter as usual?

I am developing a custom keyboard.In this, I use an Enter button which works well as an enter key when I typed in a text or messaging But I want to use this button as a search key when any one type in a browser. In my keyboard, this works as newline instead of search.How can I handle this with the same button?
I am following this Link to make this Keyboard
https://code.tutsplus.com/tutorials/create-a-custom-keyboard-on-android--cms-22615
here is code
if(primaryCode == Keyboard.KEYCODE_DONE ) {
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
}
Maybe you could use:
if(primaryCode == Keyboard.KEYCODE_DONE ) {
if(Patterns.WEB_URL.matcher(editText.getText().toString()).matches()){
search();
} else {
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENTER));
}
}

keyTyped gives JTextField blank

can't solve this problem.
I want to retrieve the text that I write on my textfield with keyTyped and put int on a String. But If I do it, it gives me a blank String. What can I do?
textField_9.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e){
xw = textField_9.getText(); //should retrieve my input
}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if((!(Character.isDigit(c)) && (c!='.'))){
e.consume();
}
System.out.println(xw); //gives nothing ("") not null
numero = e.getKeyChar();
String fileName = defaultx+"\\"+"Contratti"+"\\"+textField_7.getText()+"\\"+"lista"+tipo;
Scanner scanner;
try {
scanner = new Scanner(new File(fileName));
scanner.useDelimiter(":");
while(scanner.hasNext()){
num = scanner.next();
System.out.println("Numero = "+num+"\t"+xw); //debug
dat = scanner.nextLine().replaceAll(":", "");
if(num == xw){
try(Scanner scanner1 = new Scanner(dat)){
scanner1.useDelimiter(":");
giorno = scanner1.next();
meset = scanner1.next();
anno = scanner1.next();
System.out.println(giorno+"-"+meset+"-"+anno); //debug
}catch(NoSuchElementException ex){
}
}else{
System.out.println("Dato non trovato");
}
}
scanner.close();
} catch (FileNotFoundException e1) {
} catch(NoSuchElementException e1){
}
}
});
Example
I write into my JTextField the number "5" , xw should be then "5" but instead it will be ""
Basically what I'm trying to do is to read user's input, this input (that's a number) will be searched in a .txt file that contains a list of number and dates. example : 1st line of the .txt file is "1:1-01-2017" the second line is 2:8-01-2017" the third line is "3:15:01:2017 etc..
Read this data in once not with each key press as you're trying to do above, perhaps doing this in the class's constructor. Then store the data in a searchable collection, perhaps an array list of custom class.
so what I want to do is to search in this .txt file that number before ":" and when it finds it ,write in another textfield the date. example. user write in textfield1 "3", the program will search in the .txt file the number 3 that is before the ":" and when it find it , will write the date into another textfield.
The custom class that holds the text file's data should hold the separate numbers in their own fields, and again, search the ArrayList of these objects when needed.
Also:
do not add a KeyListener to a JTextField as this can prevent the JTextField from behaving correctly (as you're finding out).
We sometimes add a DocumentListener or a DocumentFilter to the JTextField's Document for similar behaviors...
But in your case I wouldn't do either. Instead add an ActionListener to the JTextField, a listener which is activated when the ENTER key is pressed, and search the ArrayList from within this listener.
You should almost never have empty catch blocks as we see in your code above. At least print out the stacktrace, as you could very well be having problems from exceptions being thrown completely without your knowledge since your code ignores them.

How do you check if a text field in a GUI contains something?

I'm trying to check if a user's input into a text field contains certain letters and have it increment a counter if it does.
//this is the code for the button
//tfYourName is the name of the text field
//below is what I've tried already
private void btnResultsMouseClicked(java.awt.event.MouseEvent evt) {
if (tfYourName.getSelectedItems.toString.toUpperCase().contains("T"))
}
if (tfYourName.getText().toUpperCase().contains("T"))
counter++;

Why is this JTextField not showing the contents?

I am trying to make a cheat code button for my game, and the displaying of it is all fine but I cannot correctly get the contents of this text field. This is the code for it:
cheats.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
Class.console("DISPLAYED OPTIONPANE");
JOptionPane.showInputDialog(cheatCode, "Enter Code Here");
Class.console("GOT STRING" + cheatCode.getText());
if(cheatCode.getText().equals("testin")) {
Class.console("testout");
}
}
I'm pretty much a beginner at this, so help? I can post everything else if needed.
P.S. Class.console() is a thing in my driver class. It's basically a shortened version of System.out.println()
The showInputDialog() method returns the value that was entered by the user. You should capture it into a variable. For example, do this:
String userInputString = JOptionPane.showInputDialog("Enter Code Here");
The variable userInputString will be a string containing the value that you're looking for.

JTextfield Listener for Integers

I am having troubles in finding a solution to write a listener for a JTextField specifically to only allow integer values (No Strings allowed). I've tried this recommended link on Document Listener, but I don't know what method to invoke etc.
I've never used this type of Listener before, so could anyone explain how I could write a listener on a JTextField to only allow integer values that can be accepted?
Basically after I click a JButton, and before the data is extracted out onto a variable, then Listener will not allow it to be processed until an integer is inputted.
Thanks very much appreciated.
You don't want a listener, you want to get the text from the JTextField and test if it is an int.
if (!input.getText().trim().equals(""))
{
try
{
Integer.parseInt(myString);
System.out.println("An integer"):
}
catch (NumberFormatException)
{
// Not an integer, print to console:
System.out.println("This is not an integer, please only input an integer.");
// If you want a pop-up instead:
JOptionPane.showMessageDialog(frame, "Invalid input. Enter an integer.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
You could also use a regex (a little bit of overkill, but it works):
boolean isInteger = Pattern.matches("^\d*$", myString);
You don't want a document listener. You want an ActionListener on the submit/ok button.
Make sure that listener is created with a handle to the JTextField, then put this code in the actionPerformed call:
int numberInField;
try {
numberInField = Integer.parseInt(myTextField.getText());
} catch (NumberFormatException ex) {
//maybe display an error message;
JOptionPane.showMessageDialog(null, "Bad Input", "Field 'whatever' requires an integer value", JOptionPane.ERROR_MESSAGE);
return;
}
// you have a proper integer, insert code for what you want to do with it here
how I could write a listener on a JTextField to only allow integer values that can be accepted?
You should be using a JFormattedTextField or a Document Filter.
JFormattedTextField example:
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
JFormattedTextField field = new JFormattedTextField(formatter);
JOptionPane.showMessageDialog(null, field);
}
JFormattedTextField works well for restricting input. In addition to limiting input to numbers, it is capable of more advanced use, e.g. phone number format. This provides immediate validation without having to wait for form submission or similar event.

Categories