如何在JavaFx中将actionListener添加到标签 [英] How to add a actionListener to a label in JavaFx

查看:487
本文介绍了如何在JavaFx中将actionListener添加到标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户输入错误的密码或登录时将ActionListener添加到弹出的标签中. 这是我的登录控制器

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
}

我如何解决该问题?我已经尝试了很多次(setOnAction,addMouseListener),但是没有任何效果:(.

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.

预先感谢

推荐答案

标签不会触发操作事件.您可以将监听器用于鼠标单击的事件,例如:

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

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

以及在FXML文件中

<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 ;

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

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

离题注释:对变量使用正确的Java命名约定和方法名称.

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

这篇关于如何在JavaFx中将actionListener添加到标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆