由于教学的原因,编写的一个随机点名程序,废话不多说,直接上代码:

package org.example;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

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

public class MyFrame extends JFrame implements Runnable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -2874598588895179507L;
	private static List<String> LIST = new ArrayList<String>(50);
	static {
		LIST.add("宋欣航");
		LIST.add("王彤");
		LIST.add("王帅哲");
		LIST.add("赵子严");
		LIST.add("李雨涛");
		LIST.add("张佳浩");
		LIST.add("许文倩");
		LIST.add("刘宵伊");
		LIST.add("刘暄");
		LIST.add("王薪贺");
		LIST.add("陈梦鑫");
		LIST.add("曹佳豪");
	}
	private JLabel lblInfo, lblName;
	private JButton btnOK;
	private final Random ran = new Random();
	private Thread thread;
	private Font font;
	
	{
		this.lblInfo = new JLabel("当前共有" + LIST.size() + "个学生");
		this.lblName = new JLabel("姓名:");
		this.btnOK = new JButton("点名");
	    font=new Font("仿宋", Font.BOLD, 40);//设置字体样式
	    this.lblName.setForeground(Color.BLUE);//设置字体颜色(前景色)
	}

	public MyFrame() {
		this.setTitle("随机点名");//设置窗体标题
		this.setSize(255, 200);//设置窗体大小(宽和高)
		this.setLocationRelativeTo(null);//居中显示
		this.setVisible(true);//可视
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗体的退出事件绑定
		this.setLayout(new GridLayout(3, 1));//设置窗体布局为表格布局(3行1列)
		//添加控件元素到窗体中
		this.add(this.lblInfo);
		this.add(this.lblName);
		this.add(this.btnOK);
		//为按钮注册单击事件
		this.btnOK.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				//一个按钮响应多个事件(启动线程、恢复线程、挂起线程)
				String mess=e.getActionCommand();
				if(mess.equals("点名")){
					if(thread==null){
						thread=new Thread(MyFrame.this);
				        thread.start();//启动线程
					}else if(thread.isAlive()){//如果线程是活动的
						thread.resume();//恢复
					}
				    //修改按钮的文本为暂停
				    btnOK.setText("暂停");
				}else if(thread.isAlive()){
					thread.suspend();//挂起
					btnOK.setText("点名");
				}
			}
		});
	}

	@Override
	public void run() {
		while (true) {
			int m = ran.nextInt(LIST.size());//获取一个随机数
			String name=LIST.get(m);//从集合中获取姓名
			
		    this.lblName.setFont(font);	
			lblName.setText(name);//显示到label中
//			lists.remove(m);//删除已经点过的学生姓名
//			lblInfo.setText("当前共有" + lists.size() + "个学生");
			try {
				Thread.sleep(60);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		 new MyFrame();
	}
}

进一步优化后:

package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

public class ImprovedRollCall extends JFrame implements Runnable {
    private static final List<String> STUDENTS = new ArrayList<>(List.of(
            "宋欣航", "王彤", "王帅哲", "赵子严",
            "李雨涛", "张佳浩", "许文倩", "刘宵伊",
            "刘暄", "王薪贺", "陈梦鑫", "曹佳豪"
    ));
    
    private final JLabel lblInfo = new JLabel();
    private final JLabel lblName = new JLabel("姓名:");
    private final JButton btnControl = new JButton("开始");
    private final Random random = new Random();
    private volatile boolean running = false;
    private volatile boolean paused = false;
    private List<String> currentList;
    private Thread workerThread;

    public ImprovedRollCall() {
        initializeUI();
        resetList();
    }

    private void initializeUI() {
        setTitle("随机点名系统");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout(3, 1));

        // 样式设置
        Font labelFont = new Font("微软雅黑", Font.BOLD, 24);
        lblName.setFont(labelFont);
        lblName.setForeground(new Color(0, 100, 0));
        lblInfo.setHorizontalAlignment(SwingConstants.CENTER);

        btnControl.setFont(new Font("宋体", Font.BOLD, 20));
        btnControl.setBackground(new Color(70, 130, 180));
        btnControl.setForeground(Color.WHITE);

        // 组件添加
        add(lblInfo);
        add(lblName);
        add(btnControl);

        // 事件监听
        btnControl.addActionListener(this::handleControlAction);
    }

    private void handleControlAction(ActionEvent e) {
        if (!running) {
            startRollCall();
        } else if (paused) {
            resumeRollCall();
        } else {
            pauseRollCall();
        }
    }

    private void startRollCall() {
        if (currentList.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有学生已点名完毕!");
            resetList();
            return;
        }

        running = true;
        paused = false;
        workerThread = new Thread(this);
        workerThread.start();
        btnControl.setText("暂停");
        updateInfo();
    }

    private void pauseRollCall() {
        paused = true;
        btnControl.setText("继续");
    }

    private void resumeRollCall() {
        paused = false;
        synchronized (this) {
            notify();
        }
        btnControl.setText("暂停");
    }

    private void resetList() {
        currentList = new ArrayList<>(STUDENTS);
        Collections.shuffle(currentList);
        updateInfo();
    }

    private void updateInfo() {
        lblInfo.setText("剩余人数: " + currentList.size());
    }

    @Override
    public void run() {
        while (running && !currentList.isEmpty()) {
            if (paused) {
                synchronized (this) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }

            int index = random.nextInt(currentList.size());
            String name = currentList.get(index);
            
            SwingUtilities.invokeLater(() -> {
                lblName.setText(name);
            });

            try {
                Thread.sleep(80);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
        
        running = false;
        SwingUtilities.invokeLater(() -> {
            btnControl.setText("开始");
            if (currentList.isEmpty()) resetList();
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new ImprovedRollCall().setVisible(true);
        });
    }
}

打包为可执行的jar,步骤如下:

第一步:

第二步:

第三步:

第四步:

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐