将选定的值传递给新的监听器
问题描述:
因为我需要一个具有较大代码大小的动作监听器,所以我决定将一个新监听器作为一个类。 我的问题是,我需要从滚动窗格传递选定的值,所以我可以采取基于该项目的操作,它会传递一个空指针,因为侦听器甚至在我点击按钮后才会采取动作将选定的值传递给新的监听器
我的班级:
public class RecipeListener implements ActionListener{
//rest code
我的新类的构造函数是:
public RecipeListener(ArrayList<Food> foodList, String aSelectedRecipe){
this.recipesList = foodList;
this.selectedRecipe = aSelectedRecipe;
}
,我的实听众的是:
RecipeListener checkRecipeListener = new RecipeListener(breakfastArrayList, breakfastList.getSelectedValue());
按下按钮,具有从列表
EDIT第一选择的项目:这里是溶液,这是通过将JList作为参数来构造及其制造方法actionPerfomed内的字符串。 private JList tList;
public RecipeListener(ArrayList<Food> foodList, JList tempList){
/*construction arguments*/
}
public actionPerfomed(ActionEvent arg0){
String selectedRecipe = (String) tList.getSelectedValue();
//rest code
}
答
你应该定义你的听众如下:用户按下按钮后,
public class RecipeListener implements ActionListener{
//rest code
public RecipeListener(ArrayList<Food> foodList){
this.recipesList = foodList;
}
public void actionPerformed(ActionEvent e) {
String selectedReceipe = breakfastList.getSelectedValue();
// other processing code
}
在这种情况下值将被采取。
实际上,这是有效的,但是你忘了将jlist作为参数传递给构造函数,这意味着我不能像这样使用它,因为它们是2个不同的类,所以我无法直接访问jlist。无论如何,你的想法奏效了。 – Woops
@Woops当然。你是对的。我只是因为某种原因想到'RecipeListener'是一个内部类。而'breakfastList'是封闭类中的一个字段。 –
首先,我会这样做,但由于recipeListener必须比较配方的名称并打开特定的文件,每个文件都与另一个文件不同,这意味着要写入大量的代码,并且不会与其他gui组件和我已经拥有的一些小听众在同一个班上工作。再次感谢 – Woops