I am writing a simple GUI using netbeans and Java SE, i cannot seem to get input validation to work correctly. I have a JTextField and 2 JPasswordField objects, I want to check that any of these fields arent empty when the user hits the submit button. It works properly for the password fields if they are left empty, however if i input something into the username field, it prints data has been submitted, when the other form elements have not been filled with data. Here is the code below, any assistance would be greatly appreciated....
// test that none of the fields are empty before submitting form data
if (!username_input.getText().isEmpty() && !password_input1.getPassword().toString().isEmpty()
&& !password_input2.getPassword().toString().isEmpty())
{
System.out.println("Data has been submitted!");
}
else
{
System.out.println("Form has not been filled in correctly!\nPlease try again");
}
use something like
!username_input.getText().toString().equals("")&&
!new String(password_input1.getPassword()).equals("") &&
!new String(password_input2.getPassword()).equals("")
Change the boolean expression to:
!username_input.getText().isEmpty() &&
password_input1.getPassword().lenght == 0 &&
password_input2.getPassword().lenght == 0
The method getPassword() returns a char array and you need check the lenght == 0 for empty values in the JPasswordField.
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 am reading the csv file and writing it to Database ussing prepare statement but while inserting the number column ,i am getting this error
java.lang.NumberFormatException: empty String
i tried to handle by this way
if(csvLength > 43 && (null != csvRead[43] && !csvRead[43].trim().equals("\"\""))){
pstmt.setFloat(45,Float.parseFloat((csvRead[43].replac("\"","")).toString()));
}else{
pstmt.setNull(45,Types.INTEGER);
but still giving the same error .Please help
the value at csvRead[43] - """"
Because !csvRead[43].trim().equals("\"\"") is returning true, it is going inside if condition and trying yo parse "" and you are getting NumberFormatException. It should be !csvRead[43].trim().equals("").
Also I would like to suggest, create a variable for csvRead[43], you are reading thrice a value from a array. That will improve performance a bit.
if(csvLength > 43 && (null != csvRead[43] && !csvRead[43].trim().equals(""))){
pstmt.setFloat(45,Float.parseFloat((csvRead[43].replace("\"\"","0")).toString()));
}else{
pstmt.setNull(45,Types.INTEGER);
}
This does not check for an empty string:
trim().equals("\"\"")
That checks for a string whose value is two quotes. You need to check for equals("")
I have the following block of code in my Java program:
Filter.sitesToBeFiltered.add(eid.getSite());
System.out.println("Entity Site added to ArrayList. ");
Filter.applicationsToBeFiltered.add(eid.getApplication());
System.out.println("Entity Application added to ArrayList. ");
Filter.IDsToBeFiltered.add(eid.getEntity());
System.out.println("Entity ID added to ArrayList");
Filter.positionsToBeFilteredX.add(position.getX());
System.out.println("Entity X position added to ArrayList. ");
Filter.positionsToBeFilteredY.add(position.getY());
System.out.println("Entity Y position added to ArrayList. ");
Filter.positionsToBeFilteredZ.add(position.getZ());
System.out.println("Entity Z position added to ArrayList. ");
Currently, it will read the values of a set of JTextFields, and add each value to an associated ArrayList. (The ArrayLists are either ArrayLists of Integers or Doubles). However, it will read their values no matter whether the value is a String, int/ double or null...
I want to add some error checking code, so that it will only add the value to the associated ArrayList if it is of the correct data type. I've tried doing this by surrounding each of the two-line blocks in the code displayed above with an 'if' statement, such as:
if(eid.getSite() != null){
Filter.sitesToBeFiltered.add(eid.getSite());
System.out.println("Entity Site added to ArrayList. ");
}
But if I do this, I get a compile error on the if statement that says "The operator != is undefined for the argument type(s) int, null"... Why is this? What should I use to check that the value of the JTextFields are not equal to null instead?
try with:
if(eid != null && eid.getSite()) {
doSomething();
}
If it is int (primitive type) you will always get 0 if no value is set.
If for 0 nothing is assigned at UI side, then try to ignore zero if (!eid.getSite() == 0) but please make sure that 0 dont have any meaning.
With string you can cast return object to string if it's Object class, and check for not blank
I managed to solve this by adding the error checking code to where I was reading the values in from the JTextFields. So instead of:
filter1Type = String.valueOf(Gui.filter1.getSelectedItem());
filter1Value = Integer.parseInt(Gui.filter1Text.getText());
I now have:
filter1Type = String.valueOf(Gui.filter1.getSelectedItem());
if(isNumeric(Gui.filter1Text.getText()){
filter1Value = Integer.parseInt(Gui.filter1Text.getText());
} else {
filter1Value = 0;
//Display some error message to the user here.
}
So now, any value entered into the filter1Text JTextField that is not numeric will automatically be converted to 0, and a message will be displayed to the user telling them to enter a valid value.
First of all,you can control the empty TextFields using the trim method. This control must be used before you assign textField value to the arraylist.
Before control textField value is empty or not,then assign to the arraylist.
String controlledText = eid.getText().trim();//read contents of text area into 'TextField'
if(!controlledText.equals("")){
//doSometing();
}
I just started programming in java and i am creating a simple waiting list.
it al seems to work well but i decided to include a if else construction to check the textfield not beeing empty. the problem is that it seems to be ignored because i don't get a error or something.. and i googled alot for the if else example and i can't solve the problem somehow.. what am i doing wrong? below you can find the relevant code. Thanks in advance.
public void actionPerformed(ActionEvent e) {
// check if veld1 is filled in.
if ( veld1 == null || veld1.equals( "" ) ) {
// give error
System.out.println("U heeft niets ingevuld in veld1");
}
else {
veld4.setText( veld3.getText() );
veld3.setText( veld2.getText() );
veld2.setText( veld1.getText() );
textveld1.append( veld4.getText() + "\n" );
veld1.setText("");
}
}
It seems veld1 is not a string, but some Swing control.
You probably want to do
if(veld1.getText() == null || veld1.getText().equals( "" )
It is difficult to grant without seeing the rest of it, but veld1.equals("") looks suspicious. You are comparing veld1 to the empty String, but veld1 looks like a component. Maybe you meant veld1.getText().equals("") (and, similarly, veld1.getText() == null)
If the veld1 holds a JTextField, you probably want to change the statement to veld1 == null || veld1.getText() == null || veld1.getText().equals( "" ), as in your current code you check if the field itself exists, not its content.
veld1.equals("") is not the same as veld1.getText().equals(""), the first one is comparing the veld1 object to an empty string, and will always be false.
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");
}