【发布时间】:2017-12-02 01:22:43
【问题描述】:
我正在图像查看器应用程序中构建一个方法,该方法将创建幻灯片 - 在经过一段时间后,它将依次转到下一个图像。我希望这发生在无穷大,除非用户按下“esc”键。键绑定似乎是正确的解决方案,但我无法使用它们。到目前为止,这是我的代码:
private void slideshow(){
JOptionPane.showMessageDialog(null, "Press 'esc' to stop the slideshow", "Slideshow", JOptionPane.INFORMATION_MESSAGE, slideshow);
// sets the action listener that the timer triggers
ActionListener slideshowPerformer = new ActionListener() {
public void actionPerformed( ActionEvent event )
{
//goes to the next image every x seconds
nextFile();
}
};
Timer slideshowTimer = new Timer(slideshowTime, slideshowPerformer);
while(true){
//label is a JLabel
label.getInputMap().//the key binding code
}
}
尽管我已经在使用 MouseListener 浏览图像,但我愿意接受其他解决方案。
【问题讨论】:
-
与键绑定关联的
Action应该停止Timer -
@Kevin FYI
KeyListeners 很少是一个好的选择,通常会引入更多的问题然后他们解决。 Swing 重度依赖键绑定 API 来解决KeyListener遭受的问题 -
您不应该使用 while 循环。对于动画,您使用 Swing Timer。当计时器触发时,您将转到下一个图像。当您希望动画停止时,您可以停止计时器。
标签: java swing while-loop key-bindings