java - 如何访问 JMenu 上的项目并使用 Action Listener?
问题描述
我的 Java 代码遇到了动作监听器不工作的问题。我应该创建一个具有菜单栏的 GUI,当单击这些按钮时,该菜单栏会执行一些操作。例如,如果用户选择“膳食”菜单上的一个选项和“宿舍”菜单上的一个选项,它应该计算每个项目分配的值,然后输出到总成本 JField。
这就是我的代码的样子
private class MenuActionListener implements ActionListener {
//The user has chosen a new dorm or new meal plan
//Get the choices from the dormBox and mealBox and recalculate charges
//Display the new charges in the totalField
public void actionPerformed(ActionEvent arg0) {
//Get the choices from the dormBox and mealBox
int totalCost;
int dormIndex = menu.getComponentCount();
int dormCost=dormCosts[dormIndex];
int mealIndex=dorm.getComponentCount();
int mealCost=mealCosts[mealIndex];
//Calculate the charges
totalCost=dormCost+mealCost;
//Display the new charges
totalField.setText("$"+Integer.toString(totalCost));
}
}
我应该如何让它运作良好..?
解决方案
恐怕这种方法行不通。您无法从 ActionListener 内部访问您的 UI 组件。
您可能想尝试向您的 JMenuItems 添加一个匿名侦听器,以更新您的类的属性以执行计算。
编辑:检查 Holger 的答案以获得一个不错的解决方案:)
通过这种方式,您可以访问外部组件或更好地将其委托给模型类。见这里:https ://www.codejava.net/java-core/the-java-language/java-8-lambda-listener-example
推荐阅读
- javascript - 如何将 BigQuery Struct Schema 字符串转换为 Javascript 对象?
- c# - 项目不能作为插槽的父项
- python - 如何使用 Python for Azure Data Explorer 使用动态路由属性
- permissions - 为什么未安装所选组件时 MSI 安装程序会成功?
- javascript - 如何使用 Javascript 将 1 个以上的文件上传到 Amazon s3?
- google-sheets - 如何按组返回基于最新时间戳的值?
- sas - 通过 SAS 中的循环产生多个滞后?
- java - 共享首选项图像视图更改
- ios - 如何设置曲面视图的底部阴影
- python-3.x - Python 字典列表 join list com