使用操作更新另一个 class 中的实例变量

Using an action to update an instance variable in another class

所以我正在尝试使用键绑定,并且操作映射的 put() 方法采用一个操作和一个字符串参数。

/* all declartion is above
     * the class extends JPanel so the keyword "this" can be used
     * xlist is an ArrayList of Integers
     * keyActionRight ka = new keyActionRight(x); is declared above, where x is a global int
     * this is part of the keyBindingsTest class */

    xlist.add(x); 
    im = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right");

    am = this.getActionMap();
    am.put("right", ka);
    System.out.println(ka.getNextX(xlist)); //Any way for this to be called just like if I printed in the actionPerformed of the action class?

这是 keyActionRight class。当你扩展 AbstractAction:

时,它是一个动作,因为你得到一个动作
public class keyActionRight extends 
AbstractAction
{
    private int x; 
    private ArrayList<Integer> xlist;
    public keyActionRight(int x)
    {
        this.x = x;
        xlist = new ArrayList<Integer>(); 
        xlist.add(x);  
    }

    public int getNextX(ArrayList<Integer> x)
    {
        x = xlist; 
        return x.get(0);
    }

    public void actionPerformed(ActionEvent e)
    {
        if(x != 440)
        {
            x++; //this incrementing works fine
            xlist.add(0, x); //this updates xlist fine
        }  
    }
}

目标基本上只是在我按下或按住右箭头键时更新 keyBindingsTest class 中的实例变量 x。当我执行此操作时,Action class 中的 x 更新得很好(我将其打印出来并且有效)。已经指出了为什么它不更新——它只在打印语句中被调用一次。我想知道是否有办法通过单独的 class 来完成这项工作,或者我是否需要采取不同的方法。

我可以尝试在 keyBindingsTest class 中执行操作,但上次尝试时出现了奇怪的错误。任何帮助,将不胜感激。

谢谢。

你的假设有误:

xlist.add(x); 
im = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right");

am = this.getActionMap();
am.put("right", ka);

// **** the comment below is incorrect ****
//only prints out zero - should print out ascending values of x as I hold down the right arrow key
System.out.println(ka.getNextX(xlist));  

您所做的假设是在调用键绑定操作时调用 println,但事实并非如此。 println 被调用 一次 并且只有 一次 当键绑定被 创建 时。唯一重复调用的代码是 Action 的 actionPerformed 方法中的代码,即为响应事件而调用的代码。

如果您希望多次调用代码以响应事件,则必须将其放置在事件侦听器中,而不是监听器的创建代码。