【问题标题】:Using an action to update an instance variable in another class使用操作更新另一个类中的实例变量
【发布时间】:2019-03-19 00:21:49
【问题描述】:

所以我尝试使用键绑定,并且动作映射的 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 类。当你扩展 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 类中的实例变量 x。执行此操作时,Action 类中的 x 更新得很好(我打印出来并且可以正常工作)。有人指出它为什么不更新 - 它只在 print 语句中被调用一次。我想知道是否有一种方法可以使用单独的动作类来完成这项工作,或者我是否需要采取不同的方法。

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

谢谢。

【问题讨论】:

  • 将您的整个错误信息分享给我们。
  • 没有错误信息。 keyBindingsTest 中的 x 只是没有增加。或者在这种情况下,我尝试使用 ArrayLists 所以 ArrayList 没有更新。
  • 您为什么希望 println 打印多次?调用 Action 时不会调用它,而只会在创建绑定时调用一次。如果您希望它多次打印,则需要在事件中调用它,例如在 Action 的 actionPerformed 方法中。
  • 是的,这是有道理的。应该想到这个大声笑。谢谢。
  • 如果您更改问题,请回复我的回答,否则这不太公平。并且要回答您的问题(如我的回答中所述)以在激活操作时调用代码,必须从侦听器中调用代码。这几乎是故事的结尾,这对你不起作用,你还没有解释原因。也请从帮助站点阅读此部分:someone answers

标签: java swing action key-bindings


【解决方案1】:

你有错误的假设:

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 在调用 Key Bindings 操作时被调用,但事实并非如此。 println 被称为once,并且仅在键绑定被创建once。唯一被重复调用的代码是 Action 的 actionPerformed 方法中的代码,即响应事件而调用的代码。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 2015-06-09
    • 2019-05-02
    • 2023-03-28
    • 1970-01-01
    • 2020-08-24
    • 2018-07-25
    • 1970-01-01
    相关资源
    最近更新 更多