如何在 JavaFx 中向标签添加 actionListener

Mic*_*ael 3 label javafx hyperlink

我正在尝试将一个 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
}
Run Code Online (Sandbox Code Playgroud)

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

如果您不介意,我还会询问 public void 初始化函数。它是做什么用的?当我创建类时它会自动弹出。

提前致谢

Jam*_*s_D 5

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

@FXML
private void gotoGoogle() {
    // open url etc
}
Run Code Online (Sandbox Code Playgroud)

并在 FXML 文件中

@FXML
private void gotoGoogle() {
    // open url etc
}
Run Code Online (Sandbox Code Playgroud)

然而,为此使用 a 可能更有意义Hyperlink,这会给用户更好的视觉反馈,即他们应该点击的东西。只需将标签替换为

<Label fx:id="IncorrectDataLabel" onMouseClicked="#gotoGoogle" ... />
Run Code Online (Sandbox Code Playgroud)

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

@FXML
private Hyperlink IncorrectDataLabel ;
Run Code Online (Sandbox Code Playgroud)

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

题外话:为变量和方法名称使用正确的 Java 命名约定