一、界面设计
this.setSize(400,300);
this.setTitle("抽奖软件");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setLayout(new FlowLayout());
JButton jbu = new JButton("开始!");
jbu.setPreferredSize(new Dimension(200,50));//设置按钮的大小
this.add(jbu);
JLabel la = new JLabel("显示抽中的奖品");
this.add(la);
this.setVisible(true);
初始化界面的大小、标题、布局,将开始按钮添加上去,这里还添加了一个标签,用于显示中奖号码,运行结果如下:
二、抽奖线程的设计
使用线程一定要继承Thread类:
public class GetThread extends Thread
抽奖结果的标签、控制什么时候暂停:
//显示抽奖结果的标签
private JLabel la;
//控制是否暂停
private boolean runit = false;
//传入界面上的显示抽奖的数字的标签组件
public GetThread(JLabel la){
this.la = la;
}
//控制线程暂停
//由界面上的按钮调用
public void changeState(){
this.runit = !runit;
}
在run()函数中重写方法:
public void run(){
while (true){
if(this.runit){
Random ran = new Random();
int x = ran.nextInt(300);
String msg = "中奖号码"+x;
Font font = new Font("黑体",Font.BOLD,50);
this.la.setFont(font);
this.la.setText(msg);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
由于要不停地生成中奖号码,我们将其写在一个永真循环中,用Random类中的nextInt方法生成一个随机数,设置字体的属性,再把它显示在标签上。注意runit是控制暂停的判断条件。
三、控制线程运行:
//抽奖线程一开始就在运行,
final GetThread gt = new GetThread(la);
gt.start();
//点击按钮改变抽奖线程的状态
jbu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gt.changeState();
}
});
调用Thread类中的start()函数让线程开始运行,添加鼠标监听器,点击按钮控制是否暂停抽奖线程
总结:使用线程编程一定要继承Thread类,在run方法中写代码,用start函数启动线程。
运行结果:
完整代码:
Prize类:
package p1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Prize extends JFrame {
public void init(){
this.setSize(400,300);
this.setTitle("抽奖软件");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setLayout(new FlowLayout());
JButton jbu = new JButton("开始!");
jbu.setPreferredSize(new Dimension(200,50));//设置按钮的大小
this.add(jbu);
JLabel la = new JLabel("显示抽中的奖品");
this.add(la);
this.setVisible(true);
//抽奖线程一开始就在运行,
final GetThread gt = new GetThread(la);
gt.start();
//点击按钮改变抽奖线程的状态
jbu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gt.changeState();
}
});
}
public static void main(String[] args) {
Prize draw = new Prize();
draw.init();
}
}
GetThread类:
package p1;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class GetThread extends Thread{
//显示抽奖结果的标签
private JLabel la;
//控制是否暂停
private boolean runit = false;
//传入界面上的显示抽奖的数字的标签组件
public GetThread(JLabel la){
this.la = la;
}
//控制线程暂停
//由界面上的按钮调用
public void changeState(){
this.runit = !runit;
}
public void run(){
while (true){
if(this.runit){
Random ran = new Random();
int x = ran.nextInt(300);
String msg = "中奖号码"+x;
Font font = new Font("黑体",Font.BOLD,50);
this.la.setFont(font);
this.la.setText(msg);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}