随机抽奖小程序

本实例使用随机数字生成5位抽奖号码,并显示在窗体的5个文本框中。当用户单击"开始"按钮时,将启动一个线程对象为5个文本框生成随机数字。单击"抽奖"按钮时,线程对象停止运行,并且将准确的中奖号码显示在信息文本框中。

开发一个抽奖小工具的实例。

(1)自定义文本框组件,把5个生成随机数的文本框的公共属性抽象定义到该文本框。

package com.lzw;  
import java.awt.Font;  
import javax.swing.JTextField;  
import javax.swing.SwingConstants;  
//自定义的文本框组件  
public class NumField extends JTextField {  
    private static final Font numfont = new Font("", Font.BOLD, 48);//定义文本框使用的字体  
   public NumField() {  
        super();   //执行父类构造方法  
        setHorizontalAlignment(SwingConstants.CENTER);  //设置文本居中对齐  
        setFont(numfont);   //设置字体  
        setFocusable(false); //取消焦点  
    }  
} 

(2)编写抽奖窗体。

public class Lottery extends JFrame {  
    private JTextField infoField;       //抽奖号码确认文本框  
    private NumField[] numFields;        //随机号码文本框数组  
    private RandomNum randomThread=new RandomNum();  
    public static void main(String args[]) {  
        EventQueue.invokeLater(new Runnable() {  
            public void run() {  
                try {  
                    Lottery frame = new Lottery();  
            frame.setVisible(true);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
    }  
     //创建窗体界面的构造方法  
    public Lottery() {  
        super();  
        final BorderLayout borderLayout_1 = new BorderLayout();  
        borderLayout_1.setVgap(10);  
        getContentPane().setLayout(borderLayout_1);   //设置布局管理器  
        setBounds(100, 100, 420, 256);  
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        final JPanel contentPanel = new JPanel();   //创建中间的内容面板  
        final BorderLayout borderLayout = new BorderLayout();   
        borderLayout.setVgap(10);  
        borderLayout.setHgap(10);  
        contentPanel.setLayout(borderLayout);  //设置内容面板布局管理器  
        getContentPane().add(contentPanel);    //添加内容面板到窗体  
        final JPanel numPanel = new JPanel();  //创建显示随机数的面板  
        contentPanel.add(numPanel);            //添加随机数面板到内容面板  
        final GridLayout gridLayout = new GridLayout(1, 0);  
        gridLayout.setHgap(10);  
        numPanel.setLayout(gridLayout);    //设置随机数面板布局管理器  
        numFields = new NumField[5];      //创建随机数文本框数组  
        for(int i=0;i<numFields.length;i++){  //初始化随机数文本框  
            numFields[i]=new NumField();      //初始化数组元素  
            numPanel.add(numFields[i]);       //添加文本框到随机数面板  
        }  
        final JPanel infoPanel = new JPanel();  //创建显示抽奖号码的面板  
        infoPanel.setLayout(new BorderLayout());  //设置面板布局管理器  
        contentPanel.add(infoPanel, BorderLayout.SOUTH);  //添加面板到窗体  
        final JLabel label_1 = new JLabel();       //布局抽奖号码面板  
        label_1.setFont(new Font("", Font.BOLD, 20));  
        label_1.setText("随机抽奖的中将号码是:");  
        infoPanel.add(label_1, BorderLayout.WEST);  
        infoField = new JTextField();  
        infoPanel.add(infoField);  
        final JLabel logoLabel = new JLabel();  //布局LOGO标签  
        logoLabel.setFont(new Font("隶书",  Font.PLAIN, 72)); 
logoLabel.setHorizontalAlignment(SwingConstants.CENTER);  
        getContentPane().add(logoLabel,  BorderLayout.NORTH);  
        logoLabel.setText("随机抽奖");  
        final JPanel controlPanel = new JPanel(); //创建控制按钮面板  
        final FlowLayout flowLayout = new FlowLayout();  
        flowLayout.setHgap(25);  
        controlPanel.setLayout(flowLayout);  //设置面板布局  
        getContentPane().add(controlPanel,  BorderLayout.SOUTH);  //添加面板到窗体底部  
        final JButton startButton = new JButton();    //创建开始按钮  
        startButton.addActionListener(new ActionListener() {    //添加事件监听器  
            public void actionPerformed(final ActionEvent e) {  
            do_startButton_actionPerformed(e);  
            }  
        });  
        startButton.setText("开始");  
        controlPanel.add(startButton);        //添加按钮到面板  
        final JButton lotteryButton = new JButton();  //创建抽奖按钮  
        lotteryButton.addActionListener(new ActionListener() {      //添加事件监听器  
            public void actionPerformed(final ActionEvent e) {                    
            do_lotteryButton_actionPerformed(e);  
            }  
        });  
        lotteryButton.setText("抽奖");  
        controlPanel.add(lotteryButton);  
        final JButton exitButton = new JButton();                     //创建退出按钮  
        exitButton.addActionListener(new ActionListener() {          //添加事件监听器  
            public void actionPerformed(final ActionEvent e) {  
                  do_exitButton_actionPerformed(e);  
            }  
        });  
        exitButton.setText("退出");  
        controlPanel.add(exitButton);  
}  

     // 生成随机数字的内部线程类  
    class RandomNum extends Thread {  
        private boolean stop=false;      //线程状态变量  
        public void run() {  
            while (!stop) {  
                for (final NumField nf :  numFields) {  
                    try {  
            Thread.sleep(1);  
                    } catch (InterruptedException e) {  
                e.printStackTrace();  
                    }  
                    final int num =  (int) (Math.random() * 10);     //生成随机数  
                      
EventQueue.invokeLater(new Runnable() {  
           public void run() {  
            nf.setText(num + "");  
                        }  
                    });  
                }  
            }  
        }  

         //停止线程的方法  
             public void stopLottery() {  
            this.stop = true;  
        }  
    }  
     // 开始按钮的事件处理方法  
    protected void do_startButton_actionPerformed(final ActionEvent e) {  
        if(randomThread!=null)                    //如果存在上一个线程对象  
            randomThread.stopLottery();           //停止它  
        randomThread=new RandomNum();             //创建新的线程对象  
        randomThread.start();                     //启动线程  
}  

  
   //抽奖按钮的事件处理方法  
   
    protected void do_lotteryButton_actionPerformed(final ActionEvent e) {  
        if(randomThread!=null)              //如果存在线程对象  
            randomThread.stopLottery();     //停止它  
        try {  
            randomThread.join();            //等抽奖线程结束  
        } catch (InterruptedException e1) {  
            e1.printStackTrace();  
        }  
        EventQueue.invokeLater(new Runnable() {  //在事件队列中更新抽奖信息  
            public void run() {  
                String code = "";                //抽奖代码字符串  
                for (final NumField nf :  numFields) {    //遍历数字文本框  
                    code +=  nf.getText();                 //连接5个数字字符  
                }  
                infoField.setText(code);                  //更新抽奖信息文本框  
            }  
        });  
    }  
 
     // 退出按钮的事件处理方法  
 
 protected void do_exitButton_actionPerformed(final ActionEvent e) {  
        System.exit(0);                           //退出程序  
    }  
}

 

posted @ 2017-10-29 23:22  zheting  阅读(20982)  评论(0编辑  收藏  举报