首页 > 解决方案 > 如何单击位于方法以外的其他类中的按钮

问题描述

我在触发另一个类中的按钮时遇到问题。

我已经尝试在参数中传递按钮,但是我得到了空异常错误,这与我创建的 getter 相同。

public class ButtonHolder{
    @FXML
    RadioButton radioButton;

    public void radioButtonOnClick(){
        //does something
    }
    public RadioButton getRadioButton(){
        return this.radioButton;
    }
}


public class Example{
    public void fireButton(){
        ButtonHolder buttonHolder = new ButtonHolder();
        buttonHolder.getRadioButton.fire();
    }
}

标签: javajavafx

解决方案


问题

XML(我假设您有 XML 布局)未连接到您的代码。

解决方案

就架构而言,更好的方法是将“业务”逻辑与 UI 逻辑分开。假设您有一些代码在里面radioButtonOnClick

  • 将代码移动到一个新类到它自己的merhod
  • 将所述类添加为两个类的依赖项;
  • 从你的两个类运行新方法。

如果我需要使用按钮怎么办

您可以创建它:

//A button with an empty text caption.
Button button1 = new Button();

然后调用fire ()

如果控制元素没有fire方法怎么办

RadioMenuItem这是with的示例EventHandler

MenuBar menuBar = new MenuBar();

Menu menu = new Menu("Menu 1");

RadioMenuItem choice1Item = new RadioMenuItem("Choice 1");
choice1Item.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent e) {
        System.out.println("radio toggled");
    }
});
RadioMenuItem choice2Item = new RadioMenuItem("Choice 2");
RadioMenuItem choice3Item = new RadioMenuItem("Choice 3");

ToggleGroup toggleGroup = new ToggleGroup();
toggleGroup.getToggles().add(choice1Item);
toggleGroup.getToggles().add(choice2Item);
toggleGroup.getToggles().add(choice3Item);

menu.getItems().add(choice1Item);
menu.getItems().add(choice2Item);
menu.getItems().add(choice3Item);

menuBar.getMenus().add(menu);

VBox vBox = new VBox(menuBar);

Scene scene = new Scene(vBox, 300, 275);
primaryStage.setScene(scene);
primaryStage.show();

如果我想使用 XML 中的按钮怎么办

看看 FXML 教程: https ://riptutorial.com/javafx/example/5125/example-fxml


推荐阅读