KeleQAQ 2019-11-02 01:43 采纳率: 0%
浏览 681
已采纳

JAVA怎么让计时器一开始就运行

我是想让程序一运行 JLabal标签上的文字就显示,而不是点击按钮。现在还不知道

怎么设置!!!

代码在下面

图片说明

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;


class TimeDemo extends JFrame implements ActionListener{

    JButton bStart,bStop,bContinue;
    //JLabel 标签showWord
    JLabel showWord;
    Timer time;
    int number=0,start=1;
    char[] chainWord;

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if(e.getSource()==time) {

            showWord.setText(""+chainWord[number]);
            number++;
            if(number==chainWord.length-1)
                number=0;
        }
        else if(e.getSource()==bStart)
            time.start();
        else if(e.getSource()==bContinue)
            time.restart();
        else if(e.getSource()==bStop)
            time.stop();
    }

    public TimeDemo() {
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(200, 200, 300, 180);
        //---------------------------------------------
        //创建一个计时器,每隔1000 ms 循环
        time=new Timer(1000, this);

        //创建JLabel面板
        showWord=new JLabel();

        //这里怎么设置一开始就启动?


        //创建面版显示字体格式
        showWord.setFont(new Font("宋体", Font.BOLD, 58));
        //设置显示的文字居中
        showWord.setHorizontalAlignment(JLabel.CENTER);
        //设置按钮
        bStart=new JButton("开始");
        bStop=new JButton("暂停");
        bContinue=new JButton("继续");
        //添加监视器
        bStart.addActionListener(this);
        bContinue.addActionListener(this);
        bStop.addActionListener(this);
        //添加一个JPanel容器
        JPanel pNorth=new JPanel();
        //将按钮添加到JPanel容器
        pNorth.add(bStart);
        pNorth.add(bStop);
        pNorth.add(bContinue);
        //将JLabel面板和JPanel容器添加到JFrame
        this.add(showWord,BorderLayout.CENTER);
        this.add(pNorth,BorderLayout.NORTH);
        validate();
        chainWord=new char[5];
        for (int k = 0,i='我'; k < chainWord.length;i++, k++) {
            chainWord[k]=(char)i;

        }
    }

}
public class Test13 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new TimeDemo();
    }

}
  • 写回答

1条回答 默认 最新

  • threenewbee 2019-11-02 10:25
    关注

    把time.start();写在//这里怎么设置一开始就启动?下面

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3