Mark Randy
Mark Randy

Reputation: 95

How to convert a String object into TextField Object in javafx?

I have a method that clears a text field on a mouse click event. But this method need to be implemented for every Text-Field I wanted to apply it.

Alternatively I have tried to create a common method that returns the element id and use that element id to clear the associated element. But this element id returns as a String. I cannot convert it to a Text-Field. Is there any other way to implement above logic? Thanks in advance.

public void clearUserName(MouseEvent event) {
        String textFiledName =((Control) event.getSource()).getId(); //returns as a String
    } // Cannot convert textFiledName to a TextField

Upvotes: 0

Views: 2112

Answers (2)

You can simply use following method...

public void clearUserName(MouseEvent event) {
    userName.clear(); //Here userName is the label name.
}

Upvotes: 1

fabian
fabian

Reputation: 82461

You could attach the TextFields as userData to those Controls, e.g.

Control control = ...
control.setUserData(textField);
public void clearUserName(MouseEvent event) {
    TextField textField = (TextField) ((Node) event.getSource()).getUserData();
    ...
}

If the userData property is already in use, you could also use the properties map of Node to store a reference to the TextField instead.

Using a helper method to create the TextFields could reduce the code duplication by setting the result as userData to a Control passed as parameter.

private static TextField createTextField(Control control) {
    TextField result = new TextField();
    control.setUserData(result);
    return result;
}

An alternative would be using reflection to access a field by name, but I wouldn't recommend it. This won't work for local variables, but there simply is no way to access local variables by name.


Another possibility would be to add a method for creating the TextFields that also gets the id as parameter and adds the TextFields to a Map<String, TextField>.

private final Map<String, TextField> textFields = new HashMap<>();

private TextField createTextField(String controlId) {
    TextField result = new TextField();
    textFields.put(controlId, result);
    return result;
}

public void clearUserName(MouseEvent event) {
    String textFiledName = ((Control) event.getSource()).getId();
    TextField textField = textFields.get(textFiledName);
    ...
}

Upvotes: 3

Related Questions