/* (程序头部注释开始) * 程序的版权和版本声明部分 * Copyright (c) 2011, 烟台大学计算机学院学生 * All rights reserved. * 文件名称: * 作 者: 臧鹏 * 完成日期: 2013 年 8月 13日 * 版 本 号: 001 * 对任务及求解方法的描述部分 * 输入描述: * 问题描述:利用eclipse的windowBuilder的编写的窗口程序,随机抽取幸运观众,界面通过拖拽生成,触发事件是自己写的代码,其余代码是自动生成的 * 程序输出: 首先把所有观众姓名生成数组,最后获得数组的总数量,再在姓名数组中随机抽取数组下标,根据数组下标获得幸运观众 * 程序头部的注释结束 */ package 第三章数组; import java.awt.BorderLayout; public class 抽取幸运观众 extends JFrame { private JPanel contentPane; private JTextField textField; private JTextArea textArea; private JTextArea resultArea; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { 抽取幸运观众 frame = new 抽取幸运观众(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public 抽取幸运观众() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.addKeyListener(new KeyAdapter() { // @Override public void keyPressed(KeyEvent e) { if(e.getKeyChar()!='\n'){ //不是回车字符不作处理 return; } String name = textField.getText(); if(name.isEmpty()) //如果文本框为空也不做处理 return; textArea.append(name+"\n"); //把输入人名和回车符添加到人员列表的文本域中 textField.selectAll(); //选择文本框所有内容 } }); textField.setBounds(10, 31, 132, 21); contentPane.add(textField); textField.setColumns(10); JLabel lblNewLabel = new JLabel("\u8F93\u5165\u73B0\u573A\u89C2\u4F17\u59D3\u540D\u5E76\u56DE\u8F66"); lblNewLabel.setBounds(10, 10, 153, 15); contentPane.add(lblNewLabel); textArea = new JTextArea(); textArea.setLineWrap(true); textArea.setBounds(10, 79, 132, 173); contentPane.add(textArea); JLabel label = new JLabel("\u5E78\u8FD0\u89C2\u4F17"); label.setBounds(203, 10, 54, 15); contentPane.add(label); resultArea = new JTextArea(); resultArea.setLineWrap(true); resultArea.setBounds(203, 35, 132, 217); contentPane.add(resultArea); JButton btnNewButton = new JButton("\u62BD\u53D6"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String perstring = textArea.getText(); //获取人员列表的文本 String[] personArray = perstring.split("\n");//分割字符串,生成字符串数组 int index = (int)(Math.random()*personArray.length); //生成随机数组索引 String formatArg = "本次抽取观众人员:\n\t%1$s\n恭喜%1$s成为本次幸运观众的大奖得主。" +"\n\n我们将为%1$s颁发大奖:\n过期的酸奶二十箱";//定义包含格式参数的中奖信息 String info = String.format(formatArg, personArray[index]);//为中奖信息添加人员参数 resultArea.setText(info);//在文本域中显示中奖信息 } }); btnNewButton.setBounds(345, 162, 72, 23); contentPane.add(btnNewButton); JButton button = new JButton("\u9000\u51FA"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); //退出按钮 } }); button.setBounds(345, 205, 72, 23); contentPane.add(button); } }