1.设计思路
先要创造窗体继承JFrame,然后设计两个按钮JButton。一个开始一个停止的按钮。添加一个显示框这里用JTextField用来显示。然后是名字的添加,先暂时用文本来添加。读取文本内容我用的BuffedReader通过缓冲流来解决。随机效果的产生我用线程Thread来解决O(∩_∩)O 。
我把所有的组件分成了若干个类。这样看起来更好的理解,通过对不同组件进行设计,这样看起来就更好的理解!!!
2.成品显示
3.1窗体代码展示 Windom类
import javax.swing.*;
public class Windom extends JFrame {
WenBen wenBen=new WenBen();
AnNiu anNiu =new AnNiu();
public Windom(){
//窗口标题
this.setTitle("点名");
//窗口大小
this.setSize(500,400);
//关闭窗口程序关闭
this.setDefaultCloseOperation(3);
//窗口位于中间
this.setLocationRelativeTo(null);
//关闭窗口的默认布局
this.setLayout(null);
this.add(anNiu.x);
this.add(anNiu.y);
this.add(wenBen.jt);
//窗口显示 最后用
this.setVisible(true);
}
}
3.2按钮组件设置AnNi类
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.PublicKey;
public class AnNiu {
public JButton x=new JButton("开始");
public JButton y=new JButton("停止");
public AnNiu() {
x.setBounds(80,210,120,80);
x.setFont(new Font("宋体",Font.PLAIN,30));
y.setBounds(280,210,120,80);
y.setFont(new Font("宋体",Font.PLAIN,30));
ShiJian();
}
public void ShiJian(){
x.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x.setEnabled(false);
y.setEnabled(true);
Thread t1=new Thread(new MyThread());
MyThread.t=true;
t1.start();
}
});
y.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
y.setEnabled(false);
x.setEnabled(true);
MyThread.t=false;
}
});
}
}
3.3文本显示类WenBen
import javax.swing.*;
import java.awt.*;
public class WenBen {
JTextField jt=new JTextField();
public WenBen(){
jt.setBounds(130,70,220,80);
jt.setFont(new Font("宋体",Font.PLAIN,40));
jt.setEditable(false);
jt.setHorizontalAlignment(JTextField.CENTER);
}
}
3.4随机显示类MyThread
public class MyThread extends Thread {
public static boolean t;
public MyThread() {
}
@Override
public void run() {
while (t) {
int i = text.r.nextInt(text.arrayList.size());
text.w.wenBen.jt.setText(text.arrayList.get(i));
}
}
}
3.5主函数类
import java.io.*;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Random;
import java.util.TreeMap;
public class text {
public static ArrayList<String> arrayList=new ArrayList<>();
public static Windom w=new Windom();
public static Random r=new Random();
public static void main(String[] args) throws IOException {
BufferedReader b=new BufferedReader(new FileReader("src/main/resources/a.txt"));
while (true) {
String s = b.readLine();
if(s==null){
break;
}
else {
arrayList.add(s);
}
}
b.close();
}
}
把这些放在一起就好了!!!
之后我会对这项目进行改进,添加菜单栏和容器对内容进一步完善!!!!!!!!