java加上计时_java – 让我的jProgressBar在1到100的计时器上运行

利用@ Andrew的

example,

import java.awt.GridLayout;

import java.awt.event.*;

import javax.swing.*;

class CountUpProgressBar extends JPanel {

private JProgressBar bar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);

private JLabel label = new JLabel("", JLabel.CENTER);

private Timer timer = new Timer(100, new ActionListener() {

private int counter = 1;

@Override

public void actionPerformed(ActionEvent ae) {

label.setText(String.valueOf(counter));

bar.setValue(++counter);

if (counter > 100) {

timer.stop();

}

}

});

CountUpProgressBar() {

super.setLayout(new GridLayout(0, 1));

bar.setValue(0);

timer.start();

this.add(bar);

this.add(label);

JOptionPane.showMessageDialog(null, this);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

CountUpProgressBar cdpb = new CountUpProgressBar();

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java GUI倒计时是使用Java Swing或JavaFX等GUI库实现的一个功能,通常用于计数到某个特定时间点,例如倒数计时器,游戏中的计时器,或者作为某种操作的定时器。在Java中,你可以创建一个计时任务(TimerTask),然后用`javax.swing.Timer`或`javafx.concurrent.Task`来管理这个任务。 以下是使用Swing简单实现一个倒计时计时器的基本步骤: 1. 导入必要的包: ```java import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; ``` 2. 创建一个计时器类并重写`actionPerformed`方法: ```java public class CountdownTimer extends TimerTask { private int seconds; public CountdownTimer(int seconds) { this.seconds = seconds; } @Override public void run() { if (seconds > 0) { // 减少秒数并在界面上更新显示 seconds--; updateDisplay(seconds); // 重新安排执行,直到秒数为0 schedule(this, 1000); // 每隔1秒执行一次 } else { // 倒计时结束,可能触发停止按钮或通知 stop(); } } private void updateDisplay(int seconds) { // 实现更新界面显示的方法,如JLabel、JProgressBar等 } } ``` 3. 在主窗口中设置和启动倒计时: ```java public class Main { private JFrame frame; private JButton startButton; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Main window = new Main(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public Main() { // 初始化窗口和按钮 frame = new JFrame("Countdown"); startButton = new JButton("Start"); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 创建计时器,比如5秒倒计时 Timer timer = new Timer(1000, new CountdownTimer(5)); timer.start(); } }); // 添加布局管理器和组件 // ... } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值