java添加一个当前播放时间的显示
时间: 2024-03-10 13:49:15 浏览: 12
在Java中,你可以使用javax.swing.Timer类和javax.swing.JLabel类来实现显示当前播放时间。以下是一个简单的示例代码:
```java
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class PlayerFrame extends JFrame {
private JLabel timeLabel;
public PlayerFrame() {
timeLabel = new JLabel("00:00:00");
add(timeLabel);
Timer timer = new Timer(1000, e -> {
long time = System.currentTimeMillis();
timeLabel.setText(formatTime(time));
});
timer.start();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
}
private String formatTime(long timeInMillis) {
int seconds = (int) (timeInMillis / 1000);
int minutes = seconds / 60;
int hours = minutes / 60;
return String.format("%02d:%02d:%02d", hours, minutes % 60, seconds % 60);
}
public static void main(String[] args) {
new PlayerFrame();
}
}
```
在上面的代码中,我们创建了一个JFrame并添加了一个JLabel用于显示当前播放时间。然后,我们使用javax.swing.Timer类每秒钟更新一次时间,并使用formatTime()方法格式化时间为“HH:MM:SS”格式。最后,我们在main()方法中创建了一个PlayerFrame对象,该对象将显示当前播放时间。