java - 如何单击位于方法以外的其他类中的按钮
问题描述
我在触发另一个类中的按钮时遇到问题。
我已经尝试在参数中传递按钮,但是我得到了空异常错误,这与我创建的 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();
}
}
解决方案
问题
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
推荐阅读
- javascript - CSS Global margin not working inside @media
- android - How to create user from android and save it to firebase?
- c++ - How to change the operand type in the instruction from 32bit to 64bit in LLVM?
- python - matplotlib 中 SARIMAX 绘图的问题
- node.js - 为什么节点 js 服务器将 cookie 发送给邮递员而不是在本地主机上对应用程序做出反应
- javascript - 选择自动格式化的 jQuery
- python - 使用 Django 将 Python 转换为 html
- angular - 角度如何在编辑模式下上传图像并将图像检索为字符串?
- crypto++ - 如何在 CryptoPP 中获取 ECDSA 公钥的原始位?
- spring-cloud - Spring Cloud OpenFeign vs WebClient