java - 使用操作更新另一个类中的实例变量

标签 java swing action key-bindings

所以我尝试使用键绑定(bind),并且操作映射的 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 类。它是一个 Action ,就像你扩展 AbstractAction 时得到的 Action 一样:

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 类中的实例变量 x 。当我这样做时,Action 类中的 x 更新得很好(我将其打印出来并且它有效)。有人指出了为什么它没有更新——它只在 print 语句中被调用一次。我想知道是否有办法使该操作与单独的类一起工作,或者我是否需要采取不同的方法。

我可以尝试在 keyBindingsTest 类中创建 Action,但上次尝试时出现了奇怪的错误。任何帮助,将不胜感激。

谢谢。

最佳答案

你的假设是错误的:

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));  

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

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

关于java - 使用操作更新另一个类中的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55231937/

相关文章:

java - 为什么我的 GUI 不能正常工作?

java - 将 JComboBox 绑定(bind)到 JTable

java - 单例和静态实用程序类

java - JComboBox 选择更改

c# - 封装 Action<T> 和 Func<T>?

android - ACTION_SEND Activity 因 grantUriPermission 错误而崩溃

java - 工具栏管理器 : Why separators are not displayed?

java - 在最新的 sun jre 的 bootclassloader 中加载的任何更改/工具类的方法

java - For 循环二维数组

java - 如何在 Java 中禁用 ButtonGroup 内的 JRadioButton