NullPointerException when Setting MFXTextField's Text to Null
gilad4 opened this issue · 0 comments
gilad4 commented
Issue Description
There is a NullPointerException
(NPE) thrown when changing the text of an MFXTextField
to null. This issue occurs due to missing null checks in the listeners within the MFXTextFieldSkin
class.
Steps to Reproduce
- Create a JavaFX application with an MFXTextField instance
- Initialize the MFXTextField's text with a non-null value.
- Add the MFXTextField to a scene and show the scene on a stage.
- Set the text of the MFXTextField to any non-null value (e.g., textField.setText("Initial Value")).
- Then, set the text of this MFXTextField to null (e.g., textField.setText(null)).
- Observe the NullPointerException. (On console or with
Thread.currentThread().setUncaughtExceptionHandler(...)
)
MRE
import io.github.palexdev.materialfx.controls.MFXTextField;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class MFXTextFieldNPEExample extends Application {
@Override
public void start(Stage primaryStage) {
// Set an uncaught exception handler to show a popup
Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> {
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText(throwable.toString());
alert.showAndWait();
});
});
// Create the MFXTextField with an initial non-null text value
MFXTextField textField = new MFXTextField("Initial Value");
// Create the scene and add the textField
Scene scene = new Scene(new Pane(textField), 300, 200);
// Set the scene and show the stage
primaryStage.setScene(scene);
primaryStage.setTitle("MFXTextField NPE Example");
primaryStage.show();
// Set the text of the MFXTextField to null to reproduce the issue
textField.setText(null);
}
public static void main(String[] args) {
launch(args);
}
}
Expected Behavior
The MFXTextField
should handle null values for text without throwing an exception, perhaps treating them as empty strings.
Actual Behavior
Setting the text to null causes a NullPointerException
in the addListeners
method of the MFXTextFieldSkin
class.
Proposed Solution
A simple null check can be added to the listeners in the addListeners
method. Here is the problematic code snippet:
textField.promptTextProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.isEmpty() && !isFloating()) textField.requestLayout();
});
textField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.isEmpty() && !isFloating()) textField.requestLayout();
});