getName method cannot verify JTextField from other class - java

I wanted to verify my other JTextField using InputVerifier method. What I did I set a named for a different JTextField using setName.
private void validateJTextField()
{
tfAddress.setName("tfAddress");
tfLastName.setInputVerifier(new Validation());
tfFirstName.setInputVerifier(new Validation());
tfMiddleName.setInputVerifier(new Validation());
tfNickname.setInputVerifier(new Validation());
tfAddress.setInputVerifier(new Validation());
}
Validation class
public class Validation extends InputVerifier
{
#Override
public boolean verify(JComponent input)
{
String text = null;
String name = input.getName();
if(input instanceof JTextField)
{
text = ((JTextField) input).getText();
if(text.trim().length() == 0 || text.equals(""))
{
JOptionPane.showMessageDialog(null, "Cannot left blank");
return false;//Return false if the component need to keep focus
}
else
{
try
{
Double.parseDouble(text);
JOptionPane.showMessageDialog(null, "Cannot insert numeric");
return false;
}
catch(NumberFormatException e)
{
}
}
if(text.equals("") && name.equals("tfAddress"))
{
System.out.print("This is tfAddress");
return false;
}
}
return true;//Return true if the component should give up focus
}
}
As you can see here I'm trying to validate or check if name String is equals to "tfAddress" but unfortunately it won't met the condition. Any help or tips how can I solve this?

Here in you code this statement if(text.equals("") && name.equals("tfAddress")) will never satisfied, because of if(text.trim().length() == 0 || text.equals("")) check, so text.equals("") will never return true so name.equals("tfAddress") will skip.
In the first check of if clause if the text is empty, then the code will return. So here if(text.equals("") && name.equals("tfAddress")) you can check for if(name.equals("tfAddress"))

I just solved the problem. I made a mistake on the logic. I based on the text.trim().length() == 0 || text.equals("") so when I the program runs It check first if text is empty. What I did I set the condition based on the setName method. Hoping this will help to others.
private void validateJTextField()
{
tfLastName.setName("tfLastName");
tfFirstName.setName("tfFirstName");
tfMiddleName.setName("tfMiddleName");
tfNickname.setName("tfNickname");
tfAddress.setName("tfAddress");
tfContact.setName("tfContact");
tfLastName.setInputVerifier(new Validation());
tfFirstName.setInputVerifier(new Validation());
tfMiddleName.setInputVerifier(new Validation());
tfNickname.setInputVerifier(new Validation());
tfAddress.setInputVerifier(new Validation());
tfContact.setInputVerifier(new Validation());
}
public class Validation extends InputVerifier
{
#Override
public boolean verify(JComponent input)
{
String text = null;
String cb = null;
String name = input.getName();
if(input instanceof JTextField)
{
text = ((JTextField) input).getText();
if(name.equals("tfLastName") || name.equals("tfFirstName") || name.equals("tfMiddleName") || name.equals("tfNickname"))
{
if(text.trim().length() == 0 || text.equals(""))
{
JOptionPane.showMessageDialog(null, "Cannot left blank");
return false;//Return false if the component need to keep focus
}
else
{
try
{
Double.parseDouble(text);
JOptionPane.showMessageDialog(null, "Cannot insert numeric");
return false;
}
catch(NumberFormatException e)
{
}
}
}
else if(name.equals("tfAddress"))
{
if(text.trim().length() == 0 || text.equals(""))
{
JOptionPane.showMessageDialog(null, "Cannot left blank");
return false;//Return false if the component need to keep focus
}
}
}

Related

javafx field which accepts double only

I'm trying to create a field which accepts doubles only. I want the value to be commited without the user having to click on enter. So I am setting a listener to the changes that are happening and setting the value each time.
Here is some of my code:
// Change the behaviour of the converter to avoid empty strings and values outside the defined bounds
valueFactory.setConverter(new StringConverter<Double>() {
private final DecimalFormat format = new DecimalFormat("#.##");
#Override
public String toString(Double value) {
if (value == null) {
return format.format(0);
}
return value.toString();
}
#Override
public Double fromString(String string) {
try {
if (string == null || string.trim().length() < 0 || string.trim().length() > MAX_LENGTH) {
return null;
} else {
Double newVal = format.parse(string).doubleValue();
return (newVal >= min && max >= newVal) ? newVal : null;
}
} catch (Exception ex) {
return 0.00;
}
}
});
// Define a formatter on the text entered into the field
TextFormatter<Object> textFormatter = new TextFormatter<>(c -> {
if (c.getText().matches("[^0-9.]+") && !c.getText().trim().isEmpty()) {
return null;
}
if(c.getControlNewText().length() <= MAX_LENGTH) {
try {
Double newVal = Double.valueOf(c.getControlNewText());
return (newVal >= min && max >= newVal) ? c : null;
} catch (Exception ex) {
if(c.getControlNewText().isEmpty()) {
c.setText("0.00");
} else if(c.getControlNewText().length() == 1) {
c.setText("0.00");
} else {
c.setText("");
}
return c;
}
} else {
c.setText("");
return c;
}
});
getEditor().setTextFormatter(textFormatter);
getEditor().textProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if(!newValue.trim().isEmpty()) {
try {
setValue(Double.parseDouble(newValue), amountToStepBy);
} catch(Exception e) {
setValue(min, amountToStepBy);
getEditor().setText(min.toString());
}
}
}
});
I want the user to only be able to add double numbers in the format #.## only. The problem is this fails when I enter a number like 0.00000001 and I get an exception:
java.lang.IllegalArgumentException: The start must be <= the end
at javafx.scene.control.TextInputControl.getText(TextInputControl.java:446)
at javafx.scene.control.TextInputControl.updateContent(TextInputControl.java:564)
at javafx.scene.control.TextInputControl.replaceText(TextInputControl.java:548)
at com.sun.javafx.scene.control.skin.TextFieldSkin.replaceText(TextFieldSkin.java:576)
Also the text field gets edited with the value 1.0E-8.

Code Refactoring Extract To a Method

Friends
I have below two overloaded methods which throw same ServiceException
private ModResponse updateNDelTerms(GlobalTermDeleteType item, boolean isGlobal)
{
StdTerm stdTerm = getTerm(item.getstdTermId());
if (stdTerm == null || !getBuilder().getOwnerId().equals(stdTerm.getOwnerId()))
{
throw new ServiceException(GLOBAL_TERM_TO_DELETE_DOES_NOT_EXIST_MSG,
CANNOT_DELETE_GLOBAL_TERM, GLOBAL_TERM_DOES_NOT_EXIST);
}
if (stdTerm.isGlobal() && !isGlobal)
{
throw new ServiceException(
"Global Term can not be updated: incorrect URL.",
CANNOT_UPDATE_GLOBAL_TERM, INCORRECT_URL);
}
if (stdTerm.isLocked() != null && stdTerm.isLocked())
{
throw new ServiceException("Global Term can not be updated: stdTerm is locked.",
CANNOT_UPDATE_GLOBAL_TERM, TERM_LOCKED);
}
return updateNDel(item, stdTerm);
}
Second method is
public ItemResponse<List<stdTermItemType>> copyTerm(
BigInteger stdTermId, boolean isGlobal,
boolean isFalse)
{
StdTerm stdTerm = getTerm(stdTermId);
if (stdTerm == null || !getBuilder().getOwnerId().equals(stdTerm.getOwnerId()))
{
throw new ServiceException(GLOBAL_TERM_TO_DELETE_DOES_NOT_EXIST_MSG,
CANNOT_DELETE_GLOBAL_TERM, GLOBAL_TERM_DOES_NOT_EXIST);
}
if (stdTerm.isGlobal() && !isGlobal)
{
throw new ServiceException(
"Global Term can not be updated: incorrect URL.",
CANNOT_COPY_GLOBAL_TERM, INCORRECT_URL);
}
if (stdTerm.isLocked() != null && stdTerm.isLocked())
{
throw new ServiceException("Rate sheet term can not be updated: stdTerm is locked.",
CANNOT_COPY_GLOBAL_TERM, TERM_LOCKED);
}
return copyGlobleTerm(stdTerm, pasteTermObj, isFalse);
}
I am thinking of refactoring these two methods and use Extract common code to a method ,
However due to difference in CANNOT_COPY_GLOBAL_TERM and CANNOT_UPDATE_GLOBAL_TERM which are unique to both the methods hence
Im not able to achieve Extract to a Method refactoring .
Please suggest .
private StdTerm retrieveStdTerm(BigInteger stdTermId, boolean isGlobal, String errorTerm)
{
StdTerm stdTerm = getTerm(BigInteger stdTermId);
if (stdTerm == null || !getBuilder().getOwnerId().equals(stdTerm.getOwnerId()))
{
throw new ServiceException(GLOBAL_TERM_TO_DELETE_DOES_NOT_EXIST_MSG,
CANNOT_DELETE_GLOBAL_TERM, GLOBAL_TERM_DOES_NOT_EXIST);
}
if (stdTerm.isGlobal() && !isGlobal)
{
throw new ServiceException(
"Global Term can not be updated: incorrect URL.",
errorTerm, INCORRECT_URL);
}
if (stdTerm.isLocked() != null && stdTerm.isLocked())
{
throw new ServiceException("Global Term can not be updated: stdTerm is locked.",
errorTerm, TERM_LOCKED);
}
return stdTerm;
}
private ModResponse updateNDelTerms(GlobalTermDeleteType item, boolean isGlobal)
{
StdTerm stdTerm = retrieveStdTerm(item.getstdTermId(), isGlobal,
CANNOT_DELETE_GLOBAL_TERM);
return updateNDel(item, stdTerm);
}
public ItemResponse<List<stdTermItemType>> copyTerm(BigInteger stdTermId, boolean isGlobal,
boolean isFalse)
{
StdTerm stdTerm = retrieveStdTerm(stdTermId, isGlobal, CANNOT_COPY_GLOBAL_TERM);
return copyGlobleTerm(stdTerm, pasteTermObj, isFalse);
}
Pass in the things that are different into the extracted method.
You could also turn those methods into lambdas and pass them in as well if you're running on JDK 8. Use a more functional style.

how to highlight a input field in an android application in java

i am working on an android application registration page(in java language) where it contains 13 fields. i have done validation to all the fields and its working fine with toast messages. but my requirement is if any field raises a toast message then that field should be highlighted. here is my sample code
if (driverName.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter first name", Toast.LENGTH_LONG).show();
} else if (firname) {
Toast.makeText(ApplicationActivity.this, "please enter the first name correctly", Toast.LENGTH_LONG).show();
} else if (driverName_last.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter last name", Toast.LENGTH_LONG).show();
} else if (secname) {
Toast.makeText(ApplicationActivity.this, "please enter last name correctly", Toast.LENGTH_LONG).show();
} else if (fatherName.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter father name", Toast.LENGTH_LONG).show();
} else if (fathername) {
Toast.makeText(ApplicationActivity.this, "please enter father name correctly", Toast.LENGTH_LONG).show();
}
thanks in advance
You can use setError() method as follows instead of using Toast.
input.setError("Your particular error");
where, input is your EditText.
It will set the error to particular EditText when your if condition will be wrong or according to your given condition with the particular error message.
Its the better way than displaying Toast.
EDITED WITH CODE:
if (!Common.isValidLength(fName)) {
medFirstName.setError("Invalid First Name");
}
if (!Common.isValidLength(lName)) {
medLastName.setError("Invalid Last Name");
}
if (!Common.isValidEmail(email)) {
medEmailId.setError("Invalid Email");
}
if (!Common.isValidPassword(pass)) {
medPassword.setError("Invalid Password");
}
if (!Common.isValidPassword(confirmPassword)) {
medConfirmPassword.setError("Invalid Confirm Password");
}
if (!Common.isValidMatchPassword(pass, confirmPassword)) {
medConfirmPassword.setError("Password does not match");
}
For that create one Common class and put below methods in it :
/*
* A Common function to check internet connection.
* */
public static boolean isOnline(Context c) {
try {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* A common function to check length for input.
* */
public static boolean isValidLength(String fName) {
if (fName.trim().length() > 0) {
return true;
}
return false;
}
/*
* A common function to validate Email id.
* */
public static boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
public static boolean isValidPassword(String password) {
if (password != null) {
return true;
}
return false;
}
// validating of confirm password
public static boolean isValidMatchPassword(String pass, String confirmPassword) {
if (pass.equals(confirmPassword)) {
return true;
}
return false;
}
To hightlight field you have to set foucs for e.g.
firname.requestFocus();
Note: change firname with your edittext name.
requestFocus() method will return focus to view on which it is called.
for example
else if (firname) {
Toast.makeText(ApplicationActivity.this, "please enter the first name correctly", Toast.LENGTH_LONG).show();
firname.requestFoucs(); ****// here firname is edittext****
}

How do I use contains to search through a custom object ArrayList for a particular string?

I'm completely brand new to programming (started yesterday...) and Java so excuse any stupid mistakes and really awful code (I have no clue how to order/format). I've been given a task to make an inventory of videos and I want to be able to search through the inventory to check if a particular video is there.
I know I can use contains to do this but I can't get it to work with my custom objects ArrayList (videos) and I want it to search through all the data (each InventoryRow below). I've overridden equals and HashCode but it still won't work - whenever I try to run the code it will always tell me it can't find the video even if the video is there. (FYI I use contains towards the end of my code under the rent and check functions)
I'd really appreciate any help as I've been googling all day to no avail. Also if this can't be done or another method would be better please let me know! Thanks.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
class InventoryRow {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((availability == null) ? 0 : availability.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((returndate == null) ? 0 : returndate.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InventoryRow other = (InventoryRow) obj;
if (availability == null) {
if (other.availability != null)
return false;
} else if (!availability.equals(other.availability))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (returndate == null) {
if (other.returndate != null)
return false;
} else if (!returndate.equals(other.returndate))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
private String name;
private String type;
private Character availability;
private String returndate;
public InventoryRow(String name, String type, Character availability,
String returndate) {
this.name = name;
this.type = type;
this.availability = availability;
this.returndate = returndate;
}
public String getReturndate() {
return returndate;
}
public void setReturndate(String returndate) {
this.returndate = returndate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Character getAvailability() {
return availability;
}
public void setAvailability(Character availability) {
this.availability = availability;
}
public String toString() {
return name + " " + type + " " + availability + " " + returndate;
}
}
public class InventorySort {
public static void main(String[] args) {
List<InventoryRow> videos = new ArrayList<InventoryRow>();
videos.add(new InventoryRow("Casablanca", "Old", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
"1 January 2015"));
videos.add(new InventoryRow("2012", "Regular", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Ant-Man", "New", 'Y', "1 January 2015"));
// Another ArrayList because I can't seem to search through the first
// one?
/*ArrayList<String> names = new ArrayList<String>();
names.add("Casablanca");
names.add("Jurassic Park");
names.add("2012");
names.add("Ant-Man");*/
Scanner input = new Scanner(System.in);
// Output the prompt
System.out.println("What do you want to do?");
// Wait for the user to enter a line of text
String line = input.nextLine();
// List, rent and check functions
// List function
if (line.equals("l")) {
// Sort function
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
// Rent function
} else if (line.equals("r")) {
System.out.println("Which video would you like to rent?");
String line2 = input.nextLine();
// Search through ArrayList
if (videos.contains(line2)) {
System.out.println("Video available to rent!");
} else {
System.out.println("Video unavailable to rent.");
}
// Check function
} else if (line.equals("c")) {
System.out
.println("Which video would you like to check is in the inventory?");
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(line3)) {
System.out.println("Video found!");
} else {
System.out
.println("Video not found. Please see the inventory below.");
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
// If anything else is entered
} else {
System.out
.println("The only options are to list (l), rent (r) or check (c).");
}
}
}
You can use contains. But, for the first day of programming, it might be more understandable to simply iterate over your inventory, comparing the input string with the video name:
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line3.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");
Alternative to #kilo answer, you could implement equals and hashcode method only on the name of video class and check it in the following way.
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(new Video(line3, null, null, null))) {
System.out.println("Video found!");
}
This will return contains = true only if the name matches.

New user held with searching array

I am trying to search an array and if the two Strings are matched then it will return true otherwise false, firstly i want to search to see if the account is already there if so then search Code if the two exsis then return true
public boolean searchArray(String account, String code) {
for (Accounts a : bAccounts) {
if (a.getAccount().equals(account)) {
for (Accounts c : bAccounts) {
if (c.getCode().equals(Code))
return true;
}
}
}
return false;
}
Think I've got a little lost within this search method, can anyone please help me on this, thanks. This all compiles fine but doesn't seem to return anything. I have get methods in my Accounts class which has get and set methods for Account and Sort.
public boolean searchArray(String account, String code) {
for (Accounts a : bAccounts) {
if (a.getAccount().equals(account)
&& a.getCode().equals(code)) {
return true;
}
}
return false;
}
Inner for should be removed.
You didn't mention if you'll accept nulls for account and code parameters.
If null values are possible/desirable to compare, this is what I suggest:
public boolean searchArray(String account, String code) {
for (Account a : accounts) {
if (account == null) {
if (code == null) {
if ((a.getAccount() == null) && (a.getCode() == null)) {
return true;
}
} else {
if ((a.getAccount() == null) && code.equals(a.getCode())) {
return true;
}
}
} else {
if (code == null) {
if (account.equals(a.getAccount()) && (a.getCode() == null)) {
return true;
}
} else {
if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
return true;
}
}
}
}
return false;
}
If you won't consider nulls for account and code parameters, I suggest this:
public boolean searchArray(String account, String code) {
// if you won't consider nulls then there's no need to search
// when at least one of them is null
if ((account == null) || (code == null)) {
return false;
}
for (Account a : accounts) {
if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
return true;
}
}
return false;
}
Hope it helps you

Categories