/***************************************** 題目:使用者登入。 說明:輸入:使用者資料檔user.txt(以文字檔格式儲存)。 其內容有“使用者ID”、“密碼”。 輸出:如果使用者帳號及密碼都輸入對了,則出現一個Message Box 告知使用者 “登入成功!!”的訊息。反之,則出現“帳號或密碼 錯誤!!請重新登入!”的訊息。 *************************************************/ import java.awt.*; import javax.swing.*; import java.awt.event.*; //想想還有沒有其他的東西要import //要加入 java.util才行 import java.util.*; import java.io.*; public class f8 extends JFrame implements ActionListener//名稱改一改 { Container c; //設定UI元件 JLabel tuser,tpwd; JTextField user; JPasswordField pwd; JButton bot0,bot1; //設定共用的變數與類別 public f8() //建構元,名稱改一改 { super("使用者登入"); c=getContentPane();//取得ContentPane //設定版面設定 c.setLayout(new FlowLayout(FlowLayout.CENTER));//設定為用flowlayout //初始化UI元件 tuser=new JLabel("使用者:"); tpwd=new JLabel("密碼:"); user=new JTextField(10); pwd=new JPasswordField(10); bot0=new JButton("結束"); bot1=new JButton("登入"); //將UI元件加入版面中 c.add(tuser); c.add(user); c.add(tpwd); c.add(pwd); c.add(bot1); c.add(bot0); //設定UI元件與滑鼠的事件觸發傾聽者 bot0.addActionListener(this); bot1.addActionListener(this); setSize(300,200);//設定size,顯示出去 setVisible(true); } public void paint(Graphics g) { super.paint(g);//畫出元件 } //UI元件事件處理類別寫在這裡 //滑鼠事件處理類別寫在這裡 public void actionPerformed(ActionEvent e) { if (e.getSource()==bot0)//結束 { System.exit(0); } /***透過檢查那個按鈕呼叫的,就可以判定該做的動作 ***/ if (e.getSource()==bot1)//登入 { StringTokenizer stk; String str; String id,password; int login=0;//先假設沒有login成功 /** 讀取密碼檔案 **/ id=user.getText(); password=new String(pwd.getPassword()); try { FileReader fr=new FileReader("user.txt"); BufferedReader bfr=new BufferedReader(fr); while (bfr.ready()) { str=bfr.readLine(); stk=new StringTokenizer(str," \n\t"); //取得token //比對帳號與密碼 if (id.equals(stk.nextToken()) && password.equals(stk.nextToken())) { JOptionPane.showMessageDialog(null,"登入成功!!", "登入訊息!",JOptionPane.PLAIN_MESSAGE); login=1; break; } } fr.close(); } catch(IOException e1) //如果沒有讀到 {}; //檢查是否登入成功 if (login==0) { JOptionPane.showMessageDialog(null,"帳號或密碼錯誤!!請重新登入!", "登入訊息!",JOptionPane.ERROR_MESSAGE); } } } /***主程式***/ public static void main(String args[]) //程式起點 { f8 app=new f8(); //名稱改一改,啟動UI元件 app.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); //處理視窗關閉要求 } }