利用数组随机抽取幸运观众

题目:
利用数组随机抽取幸运观众_第1张图片
用个String数组存储观众(定最大为100),观众名字显示用JTextArea完成,右边中奖信息用带滚轮的JTextArea完成,加入观众用JTextField完成。
留坑:
1、JTable的使用;
2、String里的format()方法;
3、random的使用
4、Vector的使用
代码如下:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Vector;

class Test extends JFrame implements ActionListener, KeyListener
{
    JButton select, exit;
    JTextArea customer, reward;
    JTextField add_customer;
    String name_list[] = {"Jhon", "Bob", "Tom", "Spyciy", "Brother Xiang"};
    Vector list = new Vector();

    public Test()
    {
        for(int i = 0; i < name_list.length; i ++)
            list.add(name_list[i]);

        select = new JButton("Select");
        exit = new JButton("Exit");
        select.addActionListener(this);
        exit.addActionListener(this);
        select.setMaximumSize(new Dimension(10, 20));
        exit.setMaximumSize(new Dimension(10, 20));

        reward = new JTextArea();
        reward.setSize(100, 100);
        JPanel p1 = new JPanel(new GridLayout(3, 1));
        p1.add(reward); 
        p1.add(select);     
        p1.add(exit);

        add_customer = new JTextField(10);
        add_customer.addKeyListener(this);
        customer = new JTextArea();
        customer.setSize(300, 300);
        for(int i = 0; i < name_list.length; i ++)
            customer.append(name_list[i] + "\n");
        JScrollPane jsp = new JScrollPane(customer);
        JPanel p2 = new JPanel(new GridLayout(2, 1));
        p2.add(add_customer);   p2.add(jsp);

        Container content = this.getContentPane();
        setLayout(new GridLayout(1, 2));
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        content.add(p2);
        content.add(p1);
        setSize(400, 400);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == select)
        {
            int s = (int)(Math.random() * list.size());
            String temp = list.elementAt(s) + " are rewarded!!!";
            reward.setText(temp);
        }
        else if(e.getSource() == exit)
            System.exit(0);
    }

    public void keyPressed(KeyEvent e)
    {
        if(e.getKeyChar() != '\n')
            return ;
        String name = add_customer.getText();
        list.add(name);
        customer.append(list.elementAt(list.size() - 1) + "\n");
        add_customer.setText("");
    }

    public void keyReleased(KeyEvent e){}
    public void keyTyped(KeyEvent e){}

    public static void main(String arg[])
    {
        new Test();
    }
}

你可能感兴趣的:(利用数组随机抽取幸运观众)