[英]Dynamic value not working in swing swing Timer
我正在嘗試在 java 中使用 swing 計時器 class。當我對延遲進行硬編碼時,代碼以延遲時間運行。 在這種情況下 5 秒
Timer timer= new Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("running...");
}
});
但是,當我嘗試使用構造函數動態設置延遲變量時,它以 0 毫秒延遲運行。
Timer timer= new Timer(delay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("running...");
}
});
請告訴我如何在計時器 class 中動態設置延遲。
整個代碼:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
class StartStop implements ActionListener{
JFrame f=new JFrame();
JButton startButton=new JButton("START");
JButton stopButton=new JButton("STOP");
int delay;
Timer timer= new Timer(delay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("running...");
}
});
public StartStop(int interval) {
this.delay=interval; // setting the delay variable to 5 seconds
System.out.println(delay);
startButton.setBounds(50,10,95,30);
startButton.setFocusable(false);
startButton.addActionListener(this);
stopButton.setBounds(200,10,95,30);
stopButton.setFocusable(false);
stopButton.addActionListener(this);
f.add(startButton);
f.add(stopButton);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400,100);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==startButton)
{
System.out.println("started");
start();
}
if(e.getSource()==stopButton)
{
System.out.println("stopped");
stop();
}
}
void start()
{
timer.setInitialDelay(0);
timer.start();
}
void stop()
{
timer.stop();
}
public static void main(String[] args) {
StartStop ss=new StartStop(5000); //passing a 5 second delay to constructor
}
}
當前代碼的問題是您創建了一個新的計時器,其延遲還沒有值,變為 0。您可以通過添加以下內容來解決此問題:
void start() {
timer.setDelay(delay);
timer.start();
}
它是 0,因為當你創建定時器時, delay
的值是 0。
class StartStop implements ActionListener{
JFrame f=new JFrame();
JButton startButton=new JButton("START");
JButton stopButton=new JButton("STOP");
int delay;
Timer timer;
public StartStop(int interval) {
this.delay=interval; // setting the delay variable to 5 seconds
System.out.println(delay);
timer= new Timer(delay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("running...");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.