我正在尝试使用 Java Swing
创建幻灯片。
我首先实现一个类 PicturePanel
public class PicturePanel extends JPanel {
private int counter = 0;
private ImageIcon[] images = new ImageIcon[10];
private JLabel label;
public PicturePanel()
{
for(int i = 0 ; i <images.length;i++)
{
images[counter] = new ImageIcon("check.png");
label = new JLabel();
add(label);
Timer timer = new Timer(100, new TimerListener());
}
}
private class TimerListener implements ActionListener {
public TimerListener() {
}
@Override
public void actionPerformed(ActionEvent ae) {
counter++;
//counter% =images.length;
label.setIcon(images[counter]);
}
}
}
然后我通过以下代码在我的 Jframe
中调用此类:
panProfil= new PicturePanel();
panProfil
是我表单中的 Jpanel
当我运行我的项目时,我没有收到任何错误,但我的表单中没有任何内容。有人能指出我正确的方向吗?
最佳答案
所以你还没有开始你的Timer
这就是问题所在(正如@ItachiUchiha 指出的那样)。但您需要做的另一件事是知道何时 stop()
Timer
否则它将继续运行
您想要 start()
创建 Timer
之后在构造函数中使用它。在你身上 ActionListener
,要阻止它,你需要做这样的事情。
private class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
if (counter == images.length) {
((Timer)e.getSource()).stop();
} else {
label.setIcon(images[counter]);
counter++;
}
}
}
如果您想访问Timer
从你的主 GUI 类中,这样你就可以控制它,你想要一个 getter
为它,并全局声明它
public class PicturePanel extends JPanel {
private Timer timer = null;
public PicturePanel() {
timer = new Timer(1000, new TimerListener());
}
public Timer getTimer() {
return timer;
}
}
然后您可以从主 GUI 类启动和停止它
DrawPanel panel = new DrawPanel();
Timer timer = panel.getTimer();
<小时/>
另外,我不明白创建 JLabel
的意义每次迭代并将其添加到 JPanel
。您只需要一个。
关于java - 在java swing中创建幻灯片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22198422/