今天跟大家分型一个案例:
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import com.lovo.netCRM.component.LovoButton;
import com.lovo.netCRM.component.LovoTxt;
public class LoginFrame extends JFrame{
private LovoTxt nameTxt = new LovoTxt("用户名",50,50,this);
private LovoTxt pwdTxt = new LovoTxt("密码",50,200,this);
private LogObj lo = new LogObj();
public LoginFrame(){
this.setLayout(null);
LovoButton loginButton = new LovoButton("登陆",300,300,this);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if("123".equals(nameTxt.getText()) && "456".equals(pwdTxt.getText())){
JOptionPane.showMessageDialog(null, "登陆成功");
lo.writeLog("张三在15:32:30登陆系统");
}else{
JOptionPane.showMessageDialog(null, "登陆失败");
lo.writeLog("非法用户张三在15:32:30 企图登陆系统");
}
}
});
this.setSize(500,400);
this.setVisible(true);
this.setDefaultCloseOperation(3);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
LoginFrame lf = new LoginFrame();
}
}
package test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LogObj {
public void writeLog(String info){
File f = new File("log");
if(f.exists()==false){
f.mkdir();
}
Writer w = null;
BufferedWriter bw = null;
try {
w = new FileWriter("log.txt");
bw= new BufferedWriter(w);
bw.write(info);
bw.newLine();
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
String str = s.format(new Date());
bw.write(str);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
bw.close();
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}