0

我想通过摇摆轮流(延迟 40 秒)移动图像。你能帮我吗?我写了这段代码,但它不起作用。“本垒打”有形象

public void doSomething() {
    frame.add(homer);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 600);
    frame.setTitle("Homer with thread");
    frame.setVisible(true);
    ActionListener ac = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if(e.getSource().equals(KeyEvent.VK_DOWN))
                homer.setColumn(homer.getColumn() + 3);

        }
    };
    new Timer(40000, ac).start();
}
4

1 回答 1

1

您必须使用Key BindingsSwing Timer制作此功能。

例如,你可以做这样的事情。

AbstractAction downAction = new AbstractAction() {


    @Override
    public void actionPerformed(ActionEvent e) {

            int delay = 400;// you can inject this property 
            ActionListener taskPerformer = new ActionListener(){
                  public void actionPerformed(ActionEvent evt2) {
                     //your code here

                  }

            };

                Timer timer = new Timer(delay, taskPerformer);
                timer.start();

    }};


 String key = "DOWN";
 KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
 component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
 component.getActionMap().put(key, downAction);
于 2013-06-28T12:55:36.117 回答