javaSE學習筆記——隨機點名器
阿新 • • 發佈:2019-01-27
近來上課想做一個隨機點名的小軟體,剛剛寫了一個,望大家指正。
import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.ArrayList; public class DianName extends Frame{ private String fileName="a.txt"; private File f; private FileReader fr; private BufferedReader br; private List<String> names=new ArrayList<String>(); private String strName; private Label labelName; private Button btOK; public static void main(String[] args){ DianName dn=new DianName(); dn.newFrame(); dn.read(); } public void newFrame(){ labelName=new Label("顯示姓名"); btOK=new Button("開始"); this.setLocation(300,300); this.setResizable(false); this.setSize(500,400); this.add(labelName,BorderLayout.NORTH); this.add(btOK,BorderLayout.SOUTH); this.pack(); this.setVisible(true); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); btOK.addActionListener(new ButtonAction()); } public void read(){ try{ f=new File(fileName); if(!f.exists()){ f.createNewFile(); } fr=new FileReader(f); br=new BufferedReader(fr); String str=br.readLine(); while(str!=null){ names.add(str); str=br.readLine(); } }catch(Exception e){ e.printStackTrace(); } } public void write(){ try{ int index=(int)(Math.random()*names.size()); strName=names.get(index); }catch(Exception e){ e.printStackTrace(); } } private class ButtonAction implements ActionListener{ public void actionPerformed(ActionEvent e){ write(); labelName.setText(strName); } } }