How to add a actionListener to a label in JavaFx

爷,独闯天下 提交于 2019-12-12 18:19:03

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/38855779/how-to-add-a-actionlistener-to-a-label-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!