JavaFX:有没有一种简单的方法来更改代码中onAction处理程序的方法?
我有一个登录按钮,如下所示:JavaFX:有没有一种简单的方法来更改代码中onAction处理程序的方法?,java,javafx,Java,Javafx,我有一个登录按钮,如下所示: <Button fx:id="loginButton" mnemonicParsing="false" onAction="#doLogin" prefHeight="29.0" prefWidth="127.46630859375" text="Login" /> //In the Controller class @FXML private Button loginButton = new Button(); //... //... on The
<Button fx:id="loginButton" mnemonicParsing="false" onAction="#doLogin" prefHeight="29.0" prefWidth="127.46630859375" text="Login" />
//In the Controller class
@FXML
private Button loginButton = new Button();
//...
//... on The public void initialize method of the Controller
//...
loginButton.setId("loginButton");
loginButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Button) { //always true
//Do whatever you want when the event occurs
Button temp = (Button) source;
DoSomething(temp.getId());
}
}
});
单击按钮时,我想在代码中将onAction设置为“#doLogout”
我知道有一个button.setOnAction方法,但它有ActionEvent参数,我有一个问题,在内部类中,我必须使用这个选项,我无法访问外部类中的变量,我需要这些变量
这个问题还有其他解决办法吗?试试这样的方法:
<Button fx:id="loginButton" mnemonicParsing="false" onAction="#doLogin" prefHeight="29.0" prefWidth="127.46630859375" text="Login" />
//In the Controller class
@FXML
private Button loginButton = new Button();
//...
//... on The public void initialize method of the Controller
//...
loginButton.setId("loginButton");
loginButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Button) { //always true
//Do whatever you want when the event occurs
Button temp = (Button) source;
DoSomething(temp.getId());
}
}
});
并选中它以定义按钮应执行的操作,如下所示:
loginButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
if(userLogged)
doLogout();
else
doLogin();
}
});
loginButton.setOnAction(新的EventHandler(){
@凌驾
公共无效句柄(ActionEvent e){
如果(用户记录)
doLogout();
其他的
多洛金();
}
});
将外部类的引用传递给内部类。不要创建静态的内部类