首页 > 解决方案 > 如何访问 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));
  }
}

我应该如何让它运作良好..?

标签: javaswing

解决方案


恐怕这种方法行不通。您无法从 ActionListener 内部访问您的 UI 组件。

您可能想尝试向您的 JMenuItems 添加一个匿名侦听器,以更新您的类的属性以执行计算。

编辑:检查 Holger 的答案以获得一个不错的解决方案:)

通过这种方式,您可以访问外部组件或更好地将其委托给模型类。见这里:https ://www.codejava.net/java-core/the-java-language/java-8-lambda-listener-example


推荐阅读