我想用摇摆来转动图像(延迟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();
}
答案 0 :(得分:1)
您必须使用Key Bindings
和Swing 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);