java - 定时器和带有图像的 JSlider

标签 java swing timer compiler-errors jslider

这是我的代码的一部分,但它不起作用,因为它一直说在我的 ActionListener 中找不到该符号。我不知道如何让它发挥作用。

所以基本上我想做的是让 1-8.png 中的图像根据 slider 着陆的位置以及 IDK 如何移动而移动:

private static JLabel value;
private static ImageIcon image;
private static Timer timer;
private static final int delay = 2000;
private static int newDelay;
private static int i = 1;

    timer = new Timer(delay, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        // makes the image at i appear and then goes to 2 and so on until i i = 8 and will return a 1 after. Will keep on doing so                                
            value.setIcon(new ImageIcon(i + ".png"));   
            i++;

            if(i == 8) {
            i = 1;
            }
        } 
    });
    timer.start();


}


private static class SliderChange implements ChangeListener {

    public void stateChanged(ChangeEvent event) {

        JSlider source = (JSlider) event.getSource();
        // while it is adjusting timer stops and gets the value of where the slider hits and the newDelay will be the new timer time. (So if they drag slider to 6, delay(which is 2000) will be divided by 6 to get new time
        if (!source.getValueIsAdjusting()) {
            timer.stop();
            value.setIcon(new ImageIcon(i + ".png"));
            newDelay = (delay/(int)source.getValue());
            timer = new Timer(newDelay, new Actionlistener());  
            timer.start();
        }

    }

}

但这行不通。我该如何修复它?

它指向这一行,表示有错误:

timer = new Timer(newDelay, new Actionlistener());

最佳答案

我不确定是否真的有必要每次都重新创建Timer。相反,停止它,设置它的 delay 属性并重新启动它

private static class SliderChange implements ChangeListener {

    public void stateChanged(ChangeEvent event) {

        JSlider source = (JSlider) event.getSource();
        // while it is adjusting timer stops and gets the value of where the slider hits and the newDelay will be the new timer time. (So if they drag slider to 6, delay(which is 2000) will be divided by 6 to get new time
        if (!source.getValueIsAdjusting()) {
            timer.stop();
            value.setIcon(new ImageIcon(i + ".png"));
            newDelay = (delay/(int)source.getValue());
            timer.setDelay(newDelay);
            timer.start();
        }

    }

}

问题是 timer = new Timer(newDelay, new Actionlistener()); 试图创建 interface 的实例,而不实现 的要求code>interface,这让编译器感到困惑

关于java - 定时器和带有图像的 JSlider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36168869/

相关文章:

java - 在图像上绘图

c - 定时器的用户级中断处理程序

java - 在java中生成随机数,使其平均值为特定值

java - 滚动条并导入 com.github.barteksc.pdfviewer.ScrollBar;是错误,PDF 查看器也会崩溃

java - 我的网站的数字 Assets 链接协议(protocol)不起作用

Java Swing : A list of all UIDefaults properties

java - 如何向 ARRAYLIST 添加数据

java - docker中运行的应用程序无法与elasticsearch docker连接

java - 在无状态 EJB 计时器中正确使用实例变量

c# - 如何在c#中的多个窗口窗体中添加相同的计时器