I am trying to validate user input into text boxes. I am checking whether the text box is populated or not and if it's not I need to alert the user to which text box isn't populated. My problem is that I need a way of returning which text box / variable is empty. I am aware I will need to pass 2 values in, one being the content of the text box and the other, an identifier of the text box.
Currently I have this (found on StackOverflow) which checks if each variable in the array is populated.
public boolean areAllNotEmpty(String... text){
for(String s : text) {
if(s == null || "".equals(s)) {
return false;
}
}
return true;
}
I would like it to also return something like this (commented):
public boolean areAllNotEmpty(String... text){
for(String s : text) {
if(s == null || "".equals(s)) {
// return textbox name / value OR show alert box with "Forename missing" etc
return false;
}
}
return true;
}
I implemented this method before on a C# project but it requires passing in one text box at a time with multiple method calls which I'm guessing isn't great.
public static bool IsFieldNull(TextBox currentText, string type)
{
bool allOk = false;
if (currentText.Text == "")
{
MessageBox.Show("Error - '" + type + "' field cannot be left blank, please enter some data in this field");
currentText.Focus();
return allOk;
}
else
{
allOk = true;
return allOk;
}
This is how it is called in C#.
Validation.IsFieldNull(txtBoxFixtureDate, "Fixture Date") && Validation.IsFieldNull(txtBoxTime, "Time")
If any of that doesn't make sense, let me know.
Thanks for any help.
You could pass the components to the method and return ones that are empty like this:
public List<JTextField> getEmptyFields(JTextField... textFields) {
List<JTextField> emptyFields = new ArrayList<JTextField>();
for (JTextField field : textFields) {
if (field.getText().isEmpty()) {
emptyFields.add(field);
}
}
return emptyFields;
}
Then you can just check the size() of the returned list to determine if there was an empty field and deal with them accordingly.
It's not pretty useful to validate when a submit button is pressed, it's better to validate when the error is happening. You may consider using InputVerifier . Then you know when it's in valid state or not. Apart from that if you are using java7 or above you could take a look to JLayer to decorate components which are not in valid state. See here for more examples Decorate components with JLayer.
Related
I am trying to add a search filter to a Javafx gui. I need to filter by the products id number, and have tried a series of different methods in order to add it to the if (else) block of searchable items without success. It currently will search for the text items, as well as the row number, but not the id column value. The documentation I saw only references string values. Any tips would be appreciated.
FilteredList<Part>filteredData = new FilteredList<>(allParts,p->true);
partsSearchBox.textProperty().addListener((observable,oldValue,newValue) -> {
filteredData.setPredicate(part -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (part.getPartName().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});
SortedList<Part> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(partsTableview.comparatorProperty());
partsTableview.setItems(sortedData);
you can use integer value as string by calling String.valueOf(id).
for example:
else if( String.valueOf(part.getId()).toLowerCase().contains(lowerCaseFilter))
return true;
After hours searching for an answer, finally I give up on this.
I have an FXML form with the following ComboBox:
<ComboBox fx:id="cboTipo" disable="true" prefWidth="247.0" promptText="Tipo de obra..." GridPane.columnIndex="1" GridPane.rowIndex="2" />
Which is injected in a JavaFX controller class:
#FXML
public ComboBox<Tobra> cboTipo;
The combo shows a list of Tobra (stands for: Tipo de Obra in spanish) loaded from an embedded H2 database using Eclipselink 2.7 and JPA 2.2.
I don't show to the user the value of Tobra.toString, instead I set a converter in the initialization:
#Override
public void initialize(URL url, ResourceBundle rb) {
...
Objects.requireNonNull(cboTipo, "cboTipo not injected");
...
cboTipo.setConverter(new StringConverter<Tobra>() {
#Override
public String toString(Tobra object) {
return object.getCod() + ": " + object.getNombre();
}
#Override
public Tobra fromString(String string) {
return new Tobra(string);
}
});
...
}
I have an inner class which implements Task<List<Tobra>> So I can load the data in background. Then, on succeeded:
task.setOnSucceeded(evt ->
cboTipo.setItems(FXCollections.observableArrayList(task.getValue()))
);
Of course, when showing the form I run the task inside a Thread:
new Thread(task).start();
Everything seems to work fine until the code is tested. No matters on what value I click, ALWAYS the selected value resets to the first item. I've tried to force some value from the code, and it shows up in the combobox, but when user clicks the combo to choose another value, again the selected value is reset to "first item".
This behavior only occurs when using a ComboBox with type parameters. When I create the combobox without type parameter, and then I add String values, something like this:
cboTipo.getItems().clear();
cboTipo.getItems().addAll(
tobraList.stream().map(x
-> x.getCod() + ": " + x.getNombre())
.toArray());
Everything works fine.
So I've tried doing the same with my POJO Tobra without mapping to string:
cboTipo.getItems().clear();
cboTipo.getItems().addAll(tobraList);
But the issue reappears. I've also tried declaring ComboBox cboTipo without type parameter but it neither works.
My POJO Tobra, overrides the equals method this way:
#Override
public boolean equals(Object object) {
if (!(object instanceof Tobra)) {
return false;
}
var other = (Tobra) object;
return ((this.cod == null && other.cod != null)
|| (this.cod != null && !this.cod.equals(other.cod)));
}
What am I doing wrong?
PS:
I also tried setting up my own cell factory as suggested in:
Javafx combobox with custom object displays object address though custom cell factory is used
And trying and debugging it I realized that the problem isn't the rendering of the component because the value property of ComboBox never gets updated after selection.
Your equals() method is weird.
return ((this.cod == null && other.cod != null)
|| (this.cod != null && !this.cod.equals(other.cod)));
Let's break this up. Part 1:
(this.cod == null && other.cod != null)
If cod of this Tobra is null and the cod of the other Tobra is not null, then this part is true.
Now the whole expression returns true when this happens, because you have a || operator.
Let's look at the second part.
(this.cod != null && !this.cod.equals(other.cod))
If cod of this Tobra is not null and the cod of the other Tobra are not equal, then this part is true.
This, again, looks reverse.
Most likely you need to ! the whole expression. Alternatively, you can use Objects.equals(this.cod, other.cod), which checks null for you.
Lastly, make sure you also override hashCode() and return a correct value that does not break the contract for equals(). Read the Javadoc for more details.
I solved the issue changing the equals method this way:
#Override
public boolean equals(Object object) {
if (object == null || !getClass().isAssignableFrom(object.getClass())) {
return false;
} else {
var other = (Tobra) object;
return Objects.equals(this.cod, other.cod);
}
}
Lesson: don't ever trust the autogenerated code.
So I have this method which returns true if the validation is correct:
private boolean validation() {
String emailStr = etEmail.getText().toString();
if (emailStr.trim().isEmpty()) {
etEmail.setError(getResources().getString(R.string.eroareEmpty));
return false;
} else if (!emailStr.endsWith("stud.ase.ro") && emailStr.length() <= 15) {
etEmail.setError(getResources().getString(R.string.eroareEmail));
return false;
}
return true;
}
I want to verify that the text i type in EditText etEmail contains (only at the end of the string) "stud.ase.ro", the whole string not just a part of it.
In simple words, i want to verify if the email ends with "stud.ase.ro" and nothing else.
Currently my method returns true, even if i type something unsual like "hellllllllllllooo#stud", which it shouldn't do.
To match at the end of the string, use the String.endsWith method.
if (str.endWiths("hello123#stud")) {
//bla bla
}
You might want to improve your code. You're using EditText right?
EditText.getText() does not return null
You should create a local variable for repeated code access the text inside EditText: String emailStr = etEmail.getText().toString()
It will increase readability a lot.
i want to check a list of textfield with a validation loop function
if anyone can explain me how to do this thks ;)
i do this :
public void validation()
{
List<String> list = new ArrayList<>();
list.add("LastNameTextField");
list.add("nameTextField");
list.add("ageTextField");
list.add("AdressTextField");
list.add("PhoneTextField1");
for(String check :list )
{
if(validator((check.toString()).toString()))
/*here i just want to get the field name and this value */
JOptionPane.showMessageDialog(null, check+ " Empty value");
}
}
public static boolean validator(String TextFieldTextToCheck)
{
if ((TextFieldTextToCheck== null) || (TextFieldTextToCheck.length() == 0)) {
return true ;
}
else return false;
}
i dont find the way to get the field value if anyone can help
thank you for your time
For the record, I don't have allot of Java experience. If I understand correctly, you are trying to validate the contents of several TextFields in a GUI. And the validation only makes certain that the textfield is empty. I would recommend that instead of using a collection of the textField names, you simply use a collection of references to the textfields you wish to validate.
So your ArrayList is populated with textfield references instead:
ArrayList<TextField> textFields = new ArrayList<TextField>();
textFields.add(textbox1);
textFields.add(textbox2);
textFields.add(textbox3);
textFields.add(textbox4);
You iterate through the ArrayList like before. I used a System.Out call for my own testing.:
for(TextField textField : textFields) {
if(validateTextField(textField)) {
//JOptionPane.showMessageDialog(null, textField.getText() + " Empty value");
System.out.println(textField.getName() + " has an Empty value");
}
}
The validate function now looks like this. I added a test for a NULL reference, but you could leave that out.:
public static boolean validateTextField(TextField textField) {
if(textField == null) throw new NullPointerException("The validate function received a null textfield reference. Check your loop.");
return textField.getText().length() == 0;
}
Your if condition is incorrect.
if(validator((check.toString()).toString()))
It should be corrected as:
if(YourClass.validator(check))
Explanation:
check is already String. There is not need to call toString() on it.
validator method is a static method so call it in static way as YourClass.validator where YourClass is your class name.
validator method return boolean and if expects boolean so no need to get a String again.
I would like for my ComboBoxCellEditor to be able to have 3 selections possible. Right now it only has Yes or No. I would like for it to have Yes, No, Both.
Also the combobox selection values does not show up in the table unless the cell is clicked. It is hard to tell if the table cell has a selection possible unless they click in the empty cell. I would like it to at least show the down arrow.
I have read some where that the only way you can get around this is to set a default value.
I am not sure how to add the 3rd value. I will add my code trying to add the 3rd value
How can a get the combobox show up in the table without the cell having to be clicked first?
.
public class OptionEditingSupport extends EditingSupport {
private ComboBoxCellEditor cellEditor;
public OptionEditingSupport(ColumnViewer viewer) {
super(viewer);
cellEditor = new ComboBoxCellEditor(((TableViewer)viewer).getTable(), new String[]{"Yes", "No", "Both"}, SWT.READ_ONLY);
}
protected CellEditor getCellEditor(Object element) {
return cellEditor;
}
protected boolean canEdit(Object element) {
return true;
}
protected Object getValue(Object element) {
return 0;
}
protected void setValue(Object element, Object value)
{
if((element instanceof AplotDatasetData) && (value instanceof Integer)) {
Integer choice = (Integer)value;
String option = (choice == 0? "Yes":"No":"Both"); **<- Error Here
((AplotDatasetData)element).setMarkupValue(option);
getViewer().update(element, null);
}
}
}
The conditional operator
x ? y : z
is a ternary operator, which internally does:
if(x)
y;
else
z;
Thus, you can only use it with three components. Use an if else if else instead:
Integer choice = (Integer)value;
String option = "";
if(choice == 0)
option = "Yes";
else if(choice == 1)
option = "No";
else
option = "Both";
TableEditor can be used to show any Widget on top of Table Cell. It should solve your problem with showing Combobox to let user know there is selection possible for that row and column.
I am not sure I understand your question about 3 selections.