Trying to make this field only allow letters and there is an error on the " (c !='[a-zA-Z]+') " saying invalid character constant
textField_CustomerFirstName = new JTextField();
textField_CustomerFirstName.setBounds(152, 100, 273, 22);
textField_CustomerFirstName.setColumns(10);
contentPane.add(textField_CustomerFirstName);
textField_CustomerFirstName.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
// allows only numbers and back space
char c = e.getKeyChar();
if ( ((c !='[a-zA-Z]+') && (c != KeyEvent.VK_BACK_SPACE)) {
e.consume(); // ignore event
}
}
});
First, there is a difference between event.getKeyChar() and event.getKeyCode().
Second, you can use the static methods in java.lang.Character, and I believe you may be after the following:
int code = e.getKeyCode();
char c = e.getKeyChar();
if(!Character.isLetter(c) && code!=KeyEvent.VK_BACK_SPACE) {
e.consume(); // ignore event
}
You may also want to investigate whether Character.isAlphabetic is suitable for your purposes.
Related
I've got the following code
public void keyTyped(KeyEvent e) {
int i = e.getKeyChar();
for(int j = 0; j<numbers.length; j++) {
if(i!= numbers[j]){
panel.setStatus("player must use 1-5");
return;
}}
if(!panel.isValidAssign(row, col, i)){
panel.setStatus("invalid user move");
return;
}
panel.makeAssign(row, col, i);
}
I'm trying to receive the user input as number between 1 & 5.
So far I'm only receiving the unicode for each key whereas I need the actual number.
How do I change the code to reflect this?
I'm currently working on a search method in school and I'm stuck in a newbie mistake.
I havent been programming for long and I tried searching the internet for solutions but couldnt find any. I would need to get a number range from 1-10 from the textfield and then put it as an int. Once I've done that I would have to send it to my search method which I am working on. Thanks in advance peeps.
String Value = txfSort.getText();
int NumberValue = Integer.valueOf(Value);
Probably you should first limit the input of textFields to nummeric values. You can help your self with question here: What is the recommended way to make a numeric TextField in JavaFX?
public class NumberTextField extends TextField
{
#Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Code by: Burkhard
Above code would automaticly check on entry if input is ok. So then you just check, if value is > 0 and < 10. If that is true you just call your method and use value of textField.
One way of doing described would be this:
int value = Integer.valueOf(txfSort.getText());
if(value > 0 && value < 10)
{
myMethod(value);
}
try that one:
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9')) // for numbers only
&& (caracter != '\b')) {
e.consume();
}
if (Integer.valueOf(textField.getText() + caracter) > 10) {
e.consume(); // if on the text field the numbers are bigger
// than 10, consumes the last number typed
}
}
});
I am trying to make an executable JButton (which opens a new window)radiobutton is chosen and the textfiled is filled within a specific range (the textfield should be from 1800 to 2013) . For the radiobuttons I made a default choise for now, but I cannot figure out how can I return a warning that the textfield should be filled (a number between 1800 and 2013) and if it is there then it run the program.
EDIT:
So if my code is:
JFrame ....
JPanel ....
JTextField txt = new JTextField();
JButton button = new JButton("run");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//Do things here
}
});
txt.addFocusListener(new FocusListener() {
....
}
how can I use the ItemStateListener. Should I define a listener and then what?
public void actionPerformed(ActionEvent e)
{
String s = txt.getText();
char[] cArr = s.toCharAray();
ArrayList<Character> chars = new ArrayList<Character>();
for (char c : cArr)
if (c.isDigit())
chars.add(c);
cArr = new char[chars.size()];
for (int i = 0;i<chars.size();i++)
cArr[i] = char.get(i);
s = new String(cArr);
txtField.setText(s);
if (s.equals(""))
{
// issue warning
return;
}
int input = Integer.parseInt(s);
if (input >= 1800 && input <= 2013)
{
// do stuff
}
}
Basically, read the string in the text field, remove all non-numeric characters from it, and only proceed if it is in the range specified.
I have two questions regarding character and numeric values limitation. I have listening to focus lost events and validating Name (character) and Contact (numeric) TextFields.
1. How do I restrict numeric data less then 3 digits and not allow more then 13 digits.
Below is the coding of my contact TextField for numeric:
private void txt_contactFocusLost(java.awt.event.FocusEvent evt) {
if (txt_contact.getText().equals("")) {
} else {
String contact = txt_contact.getText();
Pattern pt6 = Pattern
.compile("^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]+$");
Matcher mh6 = pt6.matcher(contact);
boolean matchFound6 = mh6.matches();
if (!(matchFound6)) {
JOptionPane.showMessageDialog(null,
"* Enter the Numaric Values only *");
txt_contact.setText("");
txt_contact.requestFocus();
}
}
}
2. How do I restrict character data less then 3 character and not allow more then 30 characters.
private void txt_nameFocusLost(java.awt.event.FocusEvent evt) {
if (txt_name.getText().equals("")) {
error2.setText("Enter Full Name");
txt_name.setText("");
} else {
String name = txt_name.getText();
Pattern pt1 = Pattern.compile("^[a-zA-Z]+([\\s][a-zA-Z]+)*$");
Matcher mh1 = pt1.matcher(name);
boolean matchFound1 = mh1.matches();
if (!(matchFound1)) {
JOptionPane.showMessageDialog(null,
"* Enter the Character Values only *");
txt_name.setText("");
txt_name.requestFocus();
} else {
error2.setText("");
}
}
}
You can do something easier:
NumberFormat numF = NumberFormat.getNumberInstance();
numF.setMaximumIntegerDigits(13);
numF.setMinimumIntegerDigits(3);
JFormattedTextField THE_FIELD = new JFormattedTextField(numF);
(The same idea for characters)
Now, only numbers are allowed, with the specified length range.
Read more about it: NumberFormat and JFormattedTextField
in the pattern you can use the statement {n,m} n- to m- times
Duo to this you can build your pattern like this
for your charackter comparison
Pattern pt6=Pattern.compile("[a-zA-Z]{3,30}"); // it says, it should be 3-30 non Digits
for the numbers it is
Pattern pt6=Pattern.compile("\\d{3,13}"); // it says, it should be 3-13 Digits
For String
public boolean validateString(String data){
char [] chars = data.toCharArray();
if(chars.length < 3 || chars.length >13)
return false;
return true;
}
For Number
public boolean validateNumber(int number){
String data = number+"";
return validateString(data);
}
I'm using this one. very simple and easy
use the method that you need or both then call where you need pass your JTextField as parameter done...
public static void setNumericOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((!Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}
public static void setCharacterOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}
I wrote the code below. It checks input from a JTextField and ensures the user is typing in numbers. If not the box flashes red and the invalid character is removed.
The tipArray[] is an array of JTextFields that I add to the JFrame with a loop.
How can I apply the following code to every possible array (tipArray[0], tipArray[1] ....tipArray[6])?
tipArray[6].addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
char keyChar = e.getKeyChar();;
char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!##$%^&*()[,]{}<>_+=|\"':;?/ ".toCharArray();
for (int i = 0; i < badCharArray.length; i++) {
if (badCharArray[i] == keyChar) {
tipArray[1].setBackground(Color.RED);
}
}
}
#Override
public void keyReleased(KeyEvent e) {
if (tipArray[6].getBackground() == Color.RED) {
if (tipArray[6].getText() != "0"){
String removeLastLetter = tipArray[1].getText().substring(0, tipArray[6].getText().length()-1);
tipArray[6].setText(removeLastLetter);
tipArray[6].setBackground(Color.WHITE);
}
}
}
});
The loops I have tried dont work:
for (int i = 0; i <= 6; i++) {
tipArray[i].addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
char keyChar = e.getKeyChar();;
char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!##$%^&*()[,]{}<>_+=|\"':;?/ ".toCharArray();
for (int x = 0; x < badCharArray.length; x++) {
if (badCharArray[x] == keyChar) {
tipArray[i].setBackground(Color.RED);
}
}
}
#Override
public void keyReleased(KeyEvent e) {
if (tipArray[i].getBackground() == Color.RED) {
if (tipArray[i].getText() != "0"){
String removeLastLetter = tipArray[i].getText().substring(0, tipArray[i].getText().length()-1);
tipArray[i].setText(removeLastLetter);
tipArray[i].setBackground(Color.WHITE);
}
}
}
});
}
^The above results in all of the variable i's after line "if (badCharArray[x] == keyChar) {" having a syntax error.
Change your counter in the for loop in the second one to be a different variable (z instead of i perhaps). You have a duplicate variable the way it is now (two i's). Also, it is recommended you use a DocumentListener, not KeyListener, for checking for invalid characters, as KeyListeners sometimes fail.