延迟移动对象

时间:2013-06-28 12:15:34

标签: java swing

我想用摇摆来转动图像(延迟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();
}

1 个答案:

答案 0 :(得分: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);