- package com.cCSSoft.zhuzf6666;
- import java.awt.GridLayout;
- import javax.swing.*;
- import javax.swing.*;
- import org.omg.CORBA.COMM_FAILURE;
- import java.awt.*;
- import java.awt.event.*;
- public class Test extends JFrame implements ActionListener {
- private static final int RED_BALL_LENGTH = 33;
- private static final int BLUE_BALL_LENGTH = 16;
- private static final int RESULT_LENGTH = 7;
- JTextField t=new JTextField(20);
- JButton b = new JButton("生成");
- JButton c = new JButton("清空");
- String copyedString = "";
- public Test() {
- this.setLayout(null);
- this.add(t);
- this.add(b);
- b.setBounds(90,50,100,30);
- this.add(c);
- c.setBounds(180,50,100,30);
- t.setHorizontalAlignment(JTextField.CENTER);
- t.setEditable(false);
- t.setBounds(10,10,400,30);
- b.addActionListener(this);//注册监听
- c.addActionListener(this);//注册监听
- //for(int i=0;i<2;i++){
- //b[i]=new JButton(s[i]);
- // b[i].addActionListener(this);//注册监听
- //b[i].setActionCommand(s[i]);
- //this.add(b[i]);
- //}
- this.setTitle("双色球序列器");
- this.setSize(430,290);
- this.setLocation(200,200);
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setResizable(false);
- this.setVisible(true);
- //JFrame frame = new JFrame();
- //JPanel panel = new JPanel();
- // panel.setLayout(new GridLayout());
- //当TextArea里的内容过长时生成滚动条
- //frame.add(panel);
- // frame.setSize(200,200);
- // frame.setVisible(true);
- }
- public String ColorBall() {
- copyedString = "";
- int reds[] = new int[RED_BALL_LENGTH];
- int blues[] = new int[BLUE_BALL_LENGTH];
- int result[] = new int[RESULT_LENGTH];
- for (int i = 0; i < RED_BALL_LENGTH; ++i) {
- reds[i] = i + 1;
- }
- for (int i = 0; i < BLUE_BALL_LENGTH; ++i) {
- blues[i] = i + 1;
- }
- int index = 0;
- for (int i = 0; i < RESULT_LENGTH - 1; ++i) {
- index = (int) (Math.random() * RED_BALL_LENGTH);
- // Avoid duplicate
- if (reds[index] == 0) {
- // Reselect if duplicate
- i--;
- continue;
- } else {
- result[i] = reds[index];
- // Mark 0 for selected number
- reds[index] = 0;
- }
- }
- // blue ball
- result[RESULT_LENGTH - 1] = blues[(int) (Math.random() * BLUE_BALL_LENGTH)];
- String split;
- for (int i = 0; i < RESULT_LENGTH; ++i) {
- split = i == RESULT_LENGTH - 2 ? " - " : " ";
- copyedString = copyedString+ result[i] + split;
- }
- return copyedString;
- }
- public static void main (String [] args) {
- new Test();
- }
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==b){
- // 1 生成随机数
- copyedString = ColorBall();
- t.setText(copyedString);
- }else if(e.getSource()==c){
- t.setText("");
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2110201410734.html
来源: http://www.codesnippet.cn/detail/2110201410734.html