标签:
用java编写一个简单的随机点名器(通过读取txt文件实现)
代码如下
package ThirdClass;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class RandomName {
JFrame rFrame = new JFrame("随机点名器"); //主面板
JLabel name = new JLabel();
JButton btn = new JButton("开始点名");//按钮
Random rd = new Random();
public void init()
{
JLabel jt = new JLabel("今天你很幸运:");//提示标签页面
jt.setHorizontalAlignment(SwingConstants.CENTER);//设置标签居中
jt.setFont(new java.awt.Font("随机点名器", 1, 35));//设置字体大小
name.setHorizontalAlignment(SwingConstants.CENTER);//设置名字显示的标签居中
btn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String n = null;
try {
n = getRandomName();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//获取随机的姓名
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
name.setText(n);//设置name标签的文字
name.setFont(new java.awt.Font(n,1,35));//设置字体
name.setForeground(Color.red);
}
});
//获取JFrame的面板
Container p = this.rFrame.getContentPane();
//设置布局方式,我采用的BordepLayout布局
p.setLayout(new BorderLayout(3,1));
//添加提示标签在北方
p.add(jt,BorderLayout.NORTH);
//添加姓名标签在中央
p.add(name,BorderLayout.CENTER);
//添加按钮在南方
p.add(btn,BorderLayout.SOUTH);
//调整大小,这个是java中无法设置标签的大小
rFrame.pack();
//设置窗体大小
rFrame.setSize(300, 300);
//设置可以显示
rFrame.setVisible(true);
}
public String getRandomName() throws IOException
{
//文件所在路径
String filePath="G:\\mingdan.txt";
//读取
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"GBK"));
//创建动态字符串数组
ArrayList list = new ArrayList();
String line = null;
//对读取文件的内容进行处理,这里只进行输出
while ((line = br.readLine()) != null) {
// 将读取到的字符串放到字符串数组中
list.add(line);
// 一行一行地输出
// System.out.println(line);
}
br.close();// 关闭文件
String[] mingdan = (String[]) list.toArray(new String[0]);
// System.out.println(“length:”+mingdan.length);
int R = (int)(Math.random()*mingdan.length);
// System.out.println(“这次的幸运儿是:”+mingdan[Random]);
return mingdan[R];
}
public static void main(String[] args)
{
RandomName rn = new RandomName();
rn.init();
}
}
标签:
来源: https://blog.csdn.net/qq_39694972/article/details/83243673