在jframe界面如何创建使用Java两小时计时器, 且可修改时间
时间: 2024-03-23 18:42:57 浏览: 14
你可以在JFrame界面中使用Java中的Timer和TimerTask类来创建一个计时器,并且可以允许用户修改时间。下面是一个示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemo extends JFrame {
private JLabel timeLabel;
private Timer timer;
private int seconds = 0;
public TimerDemo() {
setTitle("Timer Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
// 创建一个JLabel来显示计时器的时间
timeLabel = new JLabel("00:00:00");
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
timeLabel.setFont(new Font("Arial", Font.BOLD, 20));
add(timeLabel, BorderLayout.CENTER);
// 创建一个JButton来允许用户修改时间
JButton editButton = new JButton("Edit Time");
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int newSeconds = Integer.parseInt(JOptionPane.showInputDialog("Enter time in seconds:"));
seconds = newSeconds;
updateTimeLabel();
}
});
add(editButton, BorderLayout.SOUTH);
// 创建一个计时器,并且每秒钟更新一次时间
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
seconds++;
updateTimeLabel();
}
}, 0, 1000);
}
private void updateTimeLabel() {
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int secs = seconds % 60;
timeLabel.setText(String.format("%02d:%02d:%02d", hours, minutes, secs));
}
public static void main(String[] args) {
TimerDemo timerDemo = new TimerDemo();
timerDemo.setVisible(true);
}
}
```
上面的代码会创建一个JFrame界面,其中包含一个JLabel来显示计时器的时间,以及一个JButton来允许用户修改时间。计时器会每秒钟更新一次时间,并且将更新后的时间显示在JLabel中。当用户点击“Edit Time”按钮时,会弹出一个对话框,允许用户输入新的时间,然后将计时器的时间设置为用户输入的时间。