用JAVA写一个电话号码滚动抽奖器

版权声明:请尊重每一个人的劳动成果 https://blog.csdn.net/jamenu/article/details/88093306

这是我用SWING写的第一个程序的改进,也是学JAVA以来的第一个自己动手写的完整的程序。故把它的思路和过程写成一篇博客,以滋纪念和温习

先列出需要用到的知识:

  • 1.JFrame和JDialog的相关用法
  • 2.控件的动作事件监听的用法
  • 3.线程的暂停和恢复以及方法的重写
  • 4.一个向字符串数组追加字符串的算法

关于界面可以不用手撸代码,下载windowbuilder插件可以实现可视化的操作界面的布局,控件等。。。。。。
先上工程的截图
文件目录
1.在主方法的文件里创建我们的主窗口类并让它继承JFrame
可以在构造函数直接调用
setDefaultCloseOperation()
setBounds(int x,int y,int width,int height) 设置坐标位置和长宽
setResizable(boolean b) 窗口是否可以最大化,true可以,false不可以
setTitle(String str) 窗口上方的标题
setVisible(boolean b) 窗口是否可见,同上
等方法对我们的窗口类进行必要的初始化

首先,我用一个标签来做背景图片,再用一个容器覆盖这个标签,将覆盖的容器隐藏
contentPane.setOpaque(boolean b)(容器对象的这个方法可以进行隐藏false隐藏true显示)
然后在后来的容器上加入三个按钮控件,一个标签用来显示号码
用控件提供的
setText(String)
setBounds(…)
等方法来调整大小和文字

还有一步可有可无,就是为控件左上角的小图标添加图片,
方法是这样的
(图片)先用URL 对象得到图片的相应路径
早用 Icon object = new ImageIcon(URL对象)
控件.setIcon(object);这个方法虽然复杂,但在导出的时候可以把图片一起打包。
(小图标)

Image im1 = new ImageIcon(包名.class.getResource(路径)).getImage();
this.setIconImage(new ImageIcon(im1).getImage());

最好建一个包把需要用到的图片文件放在里面,好管理一点

因为我是用windowbuilder来做的界面布局,直接给出我的程序截图
windowbuilder里的截图

到这里界面布局就完成了,表面工作完成。
2.新建一个类文件继承JDialog来完成我们的号码添加功能
首先根据我们的目标功能,要实现号码的添加,我们就要实现字符串的输入,并把它保存。
这就需要一个文本框,也需要一个按钮来绑定得到我们输入的号码(字符串)
这一步比较简单
上截图如下

要弹出的对话框类

3.我们已经把表面的全都弄好了
现在我们需要开始添加动作监听了
1.主按钮要控制号码的滚动和暂停,
2.添加按钮要把添加号码的兑换框弹出
3.确认按钮要把得到的字符串写入我们在类中写好的用来提供号码的字符串数组

控件的监听代码如下

控件.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
   //这里是要发生的动作
   }
 }

通过提供的各种方法来实现功能
在这里贴出比较重要的主按钮的监听代码;

btn.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String name = btn.getText();   //得到按钮上的文本
       if(name.equals("暂停")) {   //判断字符串的值是不是一样,实现两种状态的切换
         t.toSuspend();             //暂停线程的方法
         btn.setText("继续");         //设置文本
         btn.setIcon(i3);            //加载图片
    }
    else {
        t.toRever();                //线程恢复方法
        btn.setText("暂停");
        btn.setIcon(i2);
    }
    
   }
  });

接下来省去一个一个的添加监听

4.内部类实现线程的暂停和恢复

现在已经为控件添加了必要的动作监听,下一步就是线程的实现。
有2中方法可以在程序中实现线程,
一是在内部创建一个类去继承Thread类,
二是实现Runnable接口,通过接口提供的方法来达到效果

因为没有用过第2中方法,我们用第一中方法实现
现在贴出线程类的代码,

class mythread extends Thread{
   private boolean suspend = false;     //设置一个布尔变量来控制暂停和恢复
   public synchronized void toSuspend() {  //定义暂停的方法
    suspend = true;
   }
   public synchronized void toRever() {   //定义恢复的方法
    suspend = false;
    notify();  //唤醒当前休眠,挂起的线程,没有参数
   }
   public void run() {     //重新定义线程的run方法
      while(true) {    //设置一个永久的循环
         synchronized (this) {
                 while(suspend) {  //用suspend来控制调用线程的wait()方法  
                       try {
                         wait();   //线程的停止方法
                          } catch (InterruptedException e) {
                                 // TODO Auto-generated catch block
                        e.printStackTrace();
                      }
               }
      
       }
         int rnd = new Random().nextInt(number.length); //设置一个整形数让它成为字符串的随机索引
          String str = number[rnd];
          num_area.setText(str);  //使标签显示数组中随机一个字符串
     
      }
    }
  }

5.向字符串数组追加字符串的算法,实现号码的动态添加
老实说,这个算法不是我自己想的,是看的一位C站老哥的博客里的,
当时正解了我燃眉之急,我试过用集合,也想过用整形数组(要把文本框的getText方法返回的字符串强制转化成整形,也不方便且开销大)
在这里感谢写那位我忘了名字的大哥,现在贴出他的算法

private static String[] insert(String[] arr, String str) {
     int size = arr.length;  //获取数组长度
     String[] tmp = new String[size + 1];  //新建临时字符串数组,在原来基础上长度加一
     for (int i = 0; i < size; i++){  //先遍历将原来的字符串数组数据添加到临时字符串数组
         tmp[i] = arr[i];
     }
     tmp[size] = str;  //在最后添加上需要追加的数据
     return tmp;  //返回拼接完成的字符串数组
 }

到这里这个程序就完成了
在最后贴出程序的源码

body.java

package body;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JComboBox;
import javax.swing.JButton;

public class body extends JFrame {

	private JPanel contentPane;
	
	ArrayList<String> list = new ArrayList<String>();
	String[] number = {"18317900456","13907625438"};

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					body frame = new body();
					frame.setVisible(true);
					frame.setTitle("电话号码抽奖升级");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public body() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 506, 400);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		setResizable(false);
		URL u1 = body.class.getResource("/images/background.jpg");
		Icon i1 = new ImageIcon(u1);
		URL u3 = body.class.getResource("/images/Button20.jpg");
		Icon i3 = new ImageIcon(u3);
		Image im1 = new ImageIcon(body.class.getResource("/images/freedom.png")).getImage();
		this.setIconImage(new ImageIcon(im1).getImage());
		
		JPanel panel = new JPanel();
		panel.setBounds(0, 0, 500, 365);
		contentPane.add(panel);
		panel.setOpaque(false);
		panel.setLayout(null);
		
		JLabel num_area = new JLabel();
		num_area.setBounds(72, 94, 348, 95);
		panel.add(num_area);
		num_area.setFont(new Font("微软雅黑", Font.PLAIN, 48));
		num_area.setHorizontalAlignment(SwingConstants.CENTER);
		num_area.setForeground(Color.red);
		
		
		class mythread extends Thread{
			private boolean suspend = false;
			public synchronized void toSuspend() {
				suspend = true;
			}
			public synchronized void toRever() {
				suspend = false;
				notify();
			}
			public void run() {
				while(true) {
					synchronized (this) {
						while(suspend) {
							try {
								wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						
					}
					int rnd = new Random().nextInt(number.length);
					String str = number[rnd];
					num_area.setText(str);
					
				}
			}
		}
		
		mythread t;
		t = new mythread();
		t.start();
		
		
		JButton btn = new JButton("暂停");
		btn.setBounds(117, 246, 270, 48);
		panel.add(btn);
		URL u2 = body.class.getResource("/images/Button1.jpg");
		Icon i2 = new ImageIcon(u2);
		btn.setIcon(i2);
	    btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String name = btn.getText();
				if(name.equals("暂停")) {
					t.toSuspend();
					btn.setText("继续");
					btn.setIcon(i3);
				}
				else {
					t.toRever();
					btn.setText("暂停");
					btn.setIcon(i2);
				}
				
			}
		});
	
		
		JButton button = new JButton("添加号码");
		button.setBounds(42, 307, 113, 27);
		panel.add(button);
		
		JButton confrom = new JButton("确认添加");
		confrom.setBounds(300, 307, 120, 27);
		panel.add(confrom);
		
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				 needs io = new needs();
				 
				 confrom.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						number = insert(number,io.temp);
						io.dispose();
						
					}
				});
				 
				
			}
			
			
		});
		
		
		JLabel background = new JLabel();
		background.setBounds(0, 0, 510, 365);
		contentPane.add(background);
		background.setIcon(i1);
		
	
	}
	private static String[] insert(String[] arr, String str) {
	    int size = arr.length;  //获取数组长度
	    String[] tmp = new String[size + 1];  //新建临时字符串数组,在原来基础上长度加一
	    for (int i = 0; i < size; i++){  //先遍历将原来的字符串数组数据添加到临时字符串数组
	        tmp[i] = arr[i];
	    }
	    tmp[size] = str;  //在最后添加上需要追加的数据
	    return tmp;  //返回拼接完成的字符串数组
	}
}

needs.java

package body;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class needs extends JDialog {

	private final JPanel c = new JPanel();
	public JTextField textField;
	String temp;


	/**
	 * Create the dialog.
	 */
	public needs() {
		setBounds(100, 100, 430, 281);
		getContentPane().setLayout(new BorderLayout());
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setVisible(true);
		setTitle("请输入号码");
		c.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(c, BorderLayout.CENTER);
		c.setLayout(null);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setBounds(0, 191, 418, 49);
			c.add(buttonPane);
			buttonPane.setLayout(null);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						temp = textField.getText();
						
					}
				});
				okButton.setBounds(257, 0, 113, 31);
				okButton.setActionCommand("确定");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
		}
		
		textField = new JTextField();
		textField.setBounds(56, 79, 286, 49);
		c.add(textField);
		textField.setColumns(10);
	}
}

猜你喜欢

转载自blog.csdn.net/jamenu/article/details/88093306