java抽奖程序源码及心得.docx
java抽奖程序源码及心得java抽奖程序源码及心得 代码 package liangmiao; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import java.util.Timer; import java.io.*; class lmChouJiang JFrame frame = new JFrame; JLabel label_name = new JLabel("姓名"); JLabel label_num = new JLabel("学号"); jPanel photo = new jPanel; JButton startButton = new JButton("开始抽奖"); JButton stopButton = new JButton("结束抽奖"); int index; / 保持学生信息与头像的同步 ArrayList<Student> array = null; / 存储读出来的学生信息 Timer timer; public lmChouJiang / 读取学生信息 array = new ArrayList<Student> try BufferedReader bufferReader = new BufferedReader(new FileReader( "student/stu2.txt"); StringBuffer stringBuffer = new StringBuffer; String lineContent = null; String name = "" int num = 0; while (lineContent = bufferReader.readLine) != null) / 每一行区分的标识符是空格 StringTokenizer st = new StringTokenizer(lineContent, " "); / 读取学号和姓名。每一行只有两个元素,所以I的取值就是0和1,0代表学号,1代表姓名 for (int i = 0; st.hasMoreElements; i+) String word = (String) st.nextElement; if (i = 0) num = Integer.parseInt(word); else name = word; Student student = new Student(name, num); array.add(student); catch (IOException e) e.printStackTrace; frame.getContentPane.add(BorderLayout.WEST, startButton); frame.getContentPane.add(BorderLayout.EAST, stopButton); frame.getContentPane.add(BorderLayout.NORTH, label_num); frame.getContentPane.add(BorderLayout.SOUTH, label_name); frame.getContentPane.add(BorderLayout.CENTER, photo); startButton.addActionListener(new startlButtonListener); stopButton.addActionListener(new endButtonListener); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); frame.setVisible(true); index = 0; class MyTask extends TimerTask public void run int end = (int) (Math.random * array.size); for (int i = 0; i < end; i+) label_num .setText("学号:" + String.valueOf(array.get(i).getNum); label_name.setText("姓名:" + array.get(i).getName); index = i; frame.repaint; try Thread.sleep(5); catch (Exception e) e.printStackTrace; class startlButtonListener implements ActionListener public void actionPerformed(ActionEvent event) timer = new Timer; timer.scheduleAtFixedRate(new MyTask, 0, 100); class endButtonListener implements ActionListener public void actionPerformed(ActionEvent event) timer.cancel; class jPanel extends JPanel private static final long serialVersionUID = 1L; public void paintComponent(Graphics g) Image image = new ImageIcon("image/" + index + ".jpg").getImage; g.drawImage(image, 60, 100, this); class Student private String name; private int num; public String getName return name; public void setName(String name) this.name = name; public int getNum return num; public void setNum(int num) this.num = num; public Student(String name, int num) this.name = name; this.num = num; public void print System.out.println(num + " " + name); public class choujiang public static void main(String args) lmChouJiang cj = new lmChouJiang;