如何将 actionListener 添加到 JavaFx 中的标签

How to add a actionListener to a label in JavaFx

我正在尝试将 ActionListener 添加到标签中,当用户输入错误的密码或登录时,该标签就会弹出。 这是我的登录控制器

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
}

我怎样才能解决这个问题?我已经尝试了很多次(setOnAction,addMouseListener)但没有任何效果:(.

如果您不介意,我还会询问 public void 初始化函数。它是做什么用的?它在我创建 class.

时自动弹出

提前致谢

标签不会触发动作事件。您可以为鼠标单击事件使用侦听器,例如:

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

并在 FXML 文件中

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

但是,为此使用 Hyperlink 可能更有意义,这将为用户提供更好的视觉反馈,即他们希望点击的内容。只需将标签替换为

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

并相应地更新控制器中的类型:

@FXML
private Hyperlink IncorrectDataLabel ;

您需要在 FXML 文件和控制器中为 javafx.control.Hyperlink 进行适当的导入。

题外话:使用 proper Java naming conventions 作为您的变量和方法名称。