Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a actionListener to a label in JavaFx

i'm trying to add an ActionListener to a label whitch pop out whenever user types wrong password or login. Here is my Login Controller

public class LoginController implements Initializable {

@FXML
private Label label;
@FXML
private TextField LoginField;
@FXML
private PasswordField PasswdField;
@FXML
private Button LogInButton;
@FXML
private Label IncorrectDataLabel;
//private String uri = "http://google.com";



@FXML
private void LogIn(ActionEvent event) throws IOException {
    if(LoginField.getText().equals("MKARK")&&PasswdField.getText().equals("KACZOR1"))
    {

        Parent parent = FXMLLoader.load(getClass().getResource("/fxmlFiles/MainScreen.fxml"));
        Scene MainScene = new Scene(parent);
        Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        stage.setScene(MainScene);
        stage.show();


    }
    else
    {
        IncorrectDataLabel.setVisible(true);
        // <------------------- Here I want to bind hyperlink to a label with would open the google site, whenever user clicks it.
}




@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}

How am i able to fix that issue? I've tried many times (setOnAction, addMouseListener) but nothing worked :(.

If You dont mind i would also ask about the public void initialize function. What is it for? It pop out automatically when i created the class.

Thanks in advance

like image 280
Michael Avatar asked Sep 13 '25 17:09

Michael


1 Answers

Labels do not fire action events. You could use a listener for mouse clicked events, e.g:

@FXML
private void gotoGoogle() {
    // open url etc
}

and in the FXML file

<Label fx:id="IncorrectDataLabel" onMouseClicked="#gotoGoogle" ... />

However, it probably makes more sense to use a Hyperlink for this, which would give the user better visual feedback that it was something on which they were expected to click. Just replace the label with

<Hyperlink fx:id="IncorrectDataLabel" onAction="#gotoGoogle" text="..." ... />

and update the type in the controller accordingly:

@FXML
private Hyperlink IncorrectDataLabel ;

You need the appropriate import for javafx.control.Hyperlink in both the FXML file and in the controller.

Off-topic note: use proper Java naming conventions for your variable and method names.

like image 138
James_D Avatar answered Sep 16 '25 22:09

James_D