点击开始按钮,界面连续打印一句话,点击结束按钮,停止打印
2021/12/15 23:40:13
本文主要是介绍点击开始按钮,界面连续打印一句话,点击结束按钮,停止打印,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
代码实现的功能:点击开始按钮,界面连续打印一句话,点击结束按钮,停止打印。
主要步骤:开始按钮动作监听器内使用多线程控制输出语句,多线程内使用停止按钮。
在这里插入代码片 package THREAD; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; public class Automove { Thread t;//创建一个多线程全局变量 boolean b;//创建一个布尔型变量 public static void main(String[] args) { Automove a=new Automove(); a.creat(); } public void creat() { JFrame f=new JFrame(); f.setLayout(null);//使用绝对布局 Container c=f.getContentPane(); JPanel p=new JPanel(); JButton b1=new JButton("开始"); JButton b2=new JButton("结束"); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { b=true; t=new Thread(new Runnable() { public void run() { while(b) { System.out.println("你要悄悄努力,然后惊艳所有人"); try { Thread.sleep(500);//线程休眠 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { b=false; } }); } } }); t.start(); } }); p.add(b1); p.add(b2); p.setBounds(50, 50, 120, 90); c.add(p); f.setBounds(150, 150, 300, 300); f.setVisible(true); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } }
这篇关于点击开始按钮,界面连续打印一句话,点击结束按钮,停止打印的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?