如何正确格式化ActionEvent以便JButtons工作

问题描述 投票:1回答:2

我已经设置了一些ActionListeners,但只有'Takeoff'有效。单击其他按钮时不起作用。单击它们时,没有任何反应。

我试图创建一个新的ButtonHandler,但这不起作用。

ButtonListener l = new ButtonListener();

JButton takeoff = new JButton("Takeoff");
takeoff.addActionListener(new ButtonHandler());
takeoff.addActionListener();
grid[0][2].add(takeoff);

JButton land = new JButton("Land");
land.addActionListener(new ButtonHandler());
grid[1][2].add(land);

JButton forward = new JButton("Forward");
forward.addMouseListener(new MouseHandler(l));
forward.addActionListener();
grid[2][1].add(forward);

JButton left = new JButton("Left");
left.addMouseListener(new MouseHandler());
left.addActionListener(new ButtonHandler());
left.addActionListener();
grid[3][0].add(left);


takeoff.addActionListener(l);
land.addActionListener(l);
forward.addActionListener(l);
backward.addActionListener();
left.addActionListener(l);
right.addActionListener(l);
turnLeft.addActionListener(l);
turnRight.addActionListener(l);
up.addActionListener(l);
down.addActionListener(l);
stop.addActionListener(l);

我想要做的是将机器人无人机向正确的方向移动,而不是让它静止不动。

我不确定这部分是否会有所帮助,但我的ButtonHandler实现了ActionListener。

private class ButtonHandler implements ActionListener
      {

        public void actionPerformed(ActionEvent e)
          {

            String button = e.getActionCommand();

            if (button.equals("Takeoff")) {
                RobotModel.takeoff();
            }
            else if (button.equals("Land")) {
                RobotModel.land();
            }

      else if(button.equals("Left")) {
          RobotModel.left();
          }

        }
    }
java jbutton actionevent
2个回答
1
投票

您可以使用actionCommand通过反射调用方法,例如

private void init() {
    JButton left = new JButton("Go left");
    // This
    left.setActionCommand("left");
    left.addActionListener(new MethodCallActionHandler());
    // OR that
    left.addActionListener(new MethodCallActionHandler("left"));
}

private void left() {
    // go left...
}

private class MethodCallActionHandler implements ActionListener {

    private String methodName;

    private MethodCallActionHandler() {
        super();
    } 

    private MethodCallActionHandler(String methodName) {
        this.methodName = methodName;
    } 

    public void actionPerformed(ActionEvent e)
    {
        String button = methodName != null ? methodName : e.getActionCommand();
        SurroundingClass.this.getClass().getMethod(button, new Class[] {}).invoke(SurroundingClass.this);
    }
}

您还可以将action命令作为String传递给MethodCallActionHandler。


0
投票

您可以将Action Listener类继承到当前类中,然后添加所需的方法。然后你可以做takeoff.add(this)......等等。

您也无法设置动作命令,即在按钮设置中完成。

当你设置

String button = e.getActionCommand();

这不是你做的时候设定的

JButton button = new JButton("Takeoff"); <-- This is the text associated with the button


button.setActionCommand("Takeoff");

然后它应该工作。

© www.soinside.com 2019 - 2024. All rights reserved.