【发布时间】:2021-08-14 17:08:06
【问题描述】:
我正在尝试在 java 中使用 swing Timer 类。当我对延迟进行硬编码时,代码会以延迟时间运行。在这种情况下 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...");
}
});
请告诉我如何在 Timer 类中动态设置延迟。
完整代码:
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
}
}
【问题讨论】:
-
f.setLayout(null);Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。