I've made a JTextField that restricts characters being entered unless it's numbers, letter "e", or comma . But now I realised that it restricts backspace being pressed to. How can I change it? I'll add the code, where it checks what key is being pressed, below
for (JTextField tf : listOfFields)
{
String value = tf.getText();
int n = value.length();
if (ke.getKeyChar()>= '0' && ke.getKeyChar() <= '9' || ke.getKeyChar() == ','|| ke.getKeyChar() == 'e')
{
tf.setEditable(true);
}
else
{
tf.setEditable(false);
}
}}});
To have a text field accept a numeric entry, you should use a JFormattedTextField:
JFormattedTextField field = new JFormattedTextField(
NumberFormat.getIntegerInstance());
field.setColumns(12);
To make it check both a localized number format (one that uses commas) and also the java.lang syntax (like 1e5), you can create a NumberFormatter which does both:
NumberFormatter formatter = new NumberFormatter() {
#Override
public Object stringToValue(String text)
throws ParseException {
try {
return Double.valueOf(text);
} catch (NumberFormatException ne) {
return super.stringToValue(text);
}
}
};
JFormattedTextField field = new JFormattedTextField(formatter);
field.setColumns(12);
Each field’s value can be retrieved with the getValue method:
for (JFormattedTextField tf : listOfFields) {
Number value = (Number) tf.getValue();
// ...
}
Restricting the keys typed by the user is not the correct way to guarantee numeric entry. For instance, your code would allow a user to type 123,4,45,678.
There are many keys which allow editing. Home, End, Delete, and Ctrl-A are just a few. You shouldn't try to explicitly accommodate them all with a keystroke whitelist. Let JFormattedTextField do the work of verifying the input.
If you really want to stick to this way of filtering, assuming ke is a KeyEvent, test the key code not the key char: add this condition
|| ke.getKeyCode() == KeyEvent.VK_BACK_SPACE
Related
I have written simple GUI screen that actually contains a JavaFx textField where the user enters a string and that String I have to pass to TCP client.
Now the problem is user enters a string that contains SOH as the delimiter.
SOH is nothing but "\u001". But when the user enters a String that contains this delimiters then it is removed and only the simple plain text is retrieved. How can I eliminate this. This unique character is very important for me.
For example my string is as follows:
8=FIX.4.2\u001 9=9 \u001 35=A \u001 34=1\u001 49=TTDS68AP
Observer the above String where I have the \u001 character representing SOH. But when I entered this String in the TextField then the result is like:
8=FIX.4.29=9135=A34=149=TTDS68AP
How can I get the SOH character too from the Text Field?
The problem is that javaFX TextField filters invalid characters with the following function:
private static boolean isInvalidCharacter(char c, boolean newlineIllegal, boolean tabIllegal) {
if (c == 0x7F) return true;
if (c == 0xA) return newlineIllegal;
if (c == 0x9) return tabIllegal;
if (c < 0x20) return true;
return false;
}
This happens after you paste and before the String is stored in the field. Before this function is called a custom filter can be set and applied, in this filter you can change SOH to something else; it's unicode representation ␁ is a good candidate:
textField.setTextFormatter(new TextFormatter<>((t) -> {
t.setText(t.getText().replace((char)1, '\u2401'));
return t;
}));
Adding the above will change it after it's pasted and before it's stored. When you want to use the String from the textField you need to replace it back to SOH with:
String withSOH = field.getText().replace('\u2401', (char)1);
I think the problem is that you want to enter by keyboard and see the control character in the text field:
Ctrl-A (SOH) is a known shortcut, and selects the previous character.
The control character will not be displayed in a normal font.
So I came to the following solution:
String SOH_REPR = "°"; // We show SOH as this string.
someTextField.setOnKeyPressed((ke) -> {
if (ke.getCode().getName().equals("A")
&& ke.isControlDown()
&& !ke.isAltDown()
&& !ke.isMetaDown()
&& !ke.isShiftDown()) {
TextField textField = (TextField) ke.getSource();
ke.consume();
int pos = textField.getCaretPosition();
textField.insertText(pos, SOH_REPR);
}
});
someTextField.setOnKeyReleased((ke) -> {
if (ke.getCode().getName().equals("A")
&& ke.isControlDown()
&& !ke.isAltDown()
&& !ke.isMetaDown()
&& !ke.isShiftDown()) {
ke.consume();
}
});
// Convert it back.
String text = someTextField.getText().replace(SOH_REPR, "\u0001");
Pasting text with SOHs would still needed to be done for completeness sake.
Try adding the your encoding as argument.
System.setProperty("file.encoding", "yourEncoding");
I think UTF-8 should work.
I want to add text to the EditText without losing the previous text.
Ex: when typing 74, i want to add the "4" to the text box without erasing the number "7" entered before.
public void add4()
{
res = (EditText)findViewById(R.id.editText1);
if(res.getText().toString() == "0")
{
res.setText("4");
}
else
{
// add number 4 to the remaining string
}
}
You can use the append method to append to existing text.
res.append("4");
http://developer.android.com/reference/android/widget/TextView.html#append(java.lang.CharSequence)
(As a side note, don't use == to compare strings, use .equals())
Try this:
I used the .equals method on a string object to avoid the NullPointerException that may happen if the object is null or not a string.
public void add4() {
res = (EditText)findViewById(R.id.editText1);
if( "0".equals(res.getText().toString()) )
{
res.setText("4");
}
else
{
res.append("4");
}
}
res.append("4"); or you can use res.setText(res.getText() + "4");
I wrote like this; but it fails to integer only textfields
if(textField_1.getText().length()==0)
JOptionPane.showMessageDialog(null, "enter text in textfield");
Please help...
Typically, when you are validating user input in Java, you will want to check for both null and empty string values. To check String objects for equality, you must use the .equals() method (not the == operator). Thus, a check for an empty String value might look something like this:
if ( val == null || val.trim().equals( "" ) )
{
// handle empty String case
}
else
{
// handle non-empty String case
}
Hope this helps
if(textField_1.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "enter text in textfield");
}
I'm playing around with a GUI Sudoku solver that uses an array of JTextFields (gridArray) for display and an int array (sudokuGrid) for the actual solving. When I run it and it tries to cast the JTextField strings to ints, it throws a NumberFormatException on parsing the strings into ints, specifically this message:
java.lang.NumberFormatException: For input string: ""
Here's the section of code that's causing me trouble:
// create solveButton
solveButton = new JButton("Solve It!");
solveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
// create grid and call Solve()
for(int i=0;i<9;i++) {
for(int j=0;j<9;j++) {
if (gridArray[i][j].getText() == "")
{sudokuGrid[i][j] = 0;}
else {sudokuGrid[i][j] = Integer.parseInt(gridArray[i][j].getText());}
}
} // end for loop
Solver(sudokuGrid);
// display solution
for(int i=0;i<9;i++) {
for(int j=0;j<9;j++) {
gridArray[i][j].setText(String.valueOf(sudokuGrid[i][j]));
}
} // end for loop
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(mainFrame,e.toString(),"Number Format Exception",JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(mainFrame,"Sorry, something broke, try again.","Solve Error",JOptionPane.ERROR_MESSAGE);
} // end try-catch
} // end actionPerformed()
}); // end solveButton ActionListener
I thought that the if-else would catch the empty fields and only try the parseInt if there was a value present, but if anyone can enlighten me I'd appreciate it.
Your problem is here:
if (gridArray[i][j].getText() == "")
You can't compare strings that way. Do it this way instead:
if (gridArray[i][j].getText().equals(""))
You are checking string equality using ==, which is only for reference equality. Perhaps you meant to write:
gridArray[i][j].getText().equals("")
Don't ask the TextArea for it's text, since this may be prone to be still in the editing process. Check the underlying document itself.
Document document = gridArray[i][j].getDocument();
sudokuGrid[i][j] = document.getLength() == 0 ? 0 : Integer.parseInt(document.getText(0, 1);
Also... why a JTextArea? Why not a JTextField? You might even combine this with a JSpinner with values from 0 (which is inerpreted as empty to 9.
Using == -comparison with strings does not mean checking for equality of the text (string contents), but instead equality of the String-objects (testing are they the exact same OBJECT). Use String.equals() instead.
The problem is your equality check:
gridArray[i][j].getText() == ""
This does not do what you're intending. In Java this checks whether the two strings are the same object not whether their values are equal.
You should use the String.equals() method to evaluate whether the text field is empty.
I have a TextField.PhoneNumber but I would like to filter out "+" character. In other words, I need a new constraint for TextField. Is there a way to define a new constraint with TextField?
How about preventing keys from cycling on a mobile phone within a midp?
It might not what you really want.
But, MIDP does not support change constraint rule as you want. So, I suggest HACK for your purpose.
How about use ItemStateListener to check if text field contains string which you want to filter out and if this string is exist, change text field forcefully.
The code could be looks like below:
// set item state listener
form.setItemStateListener(this);
// check if text field contains invalid string
// then replace it
public void itemStateChanged(Item item) {
if (item == getTextField()) {
TextField t = (TextField)item;
String s = t.getString();
// + is invalid string
int pos = s.indexOf("+");
if (pos != -1) {
t.setString(s.substring(0, pos) + s.substring(pos + 1));
}
}
}