一个简单的记事本代码(二)
时间:2011-01-11
/**************************************************/
//调用的函数
public void File_new_actionPerformed(ActionEvent e){
FileNew();
}
public void File_open_actionPerformed(ActionEvent e){
FileOpen();
}
public void File_save_actionPerformed(ActionEvent e){
FileSave();
}
public void File_saveto_actionPerformed(ActionEvent e){
FileSaveTo();
}
public void File_close_actionPerformed(ActionEvent e){
FileClose();
}
public void mouseReleased(MouseEvent e){
if(e.isPopupTrigger())
pm.show(this,e.getX(),e.getY());
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
boolean toExit()
{
if(bsaved)
return true;
int i=JOptionPane.showConfirmDialog(this,"是否保存文件","Jishiben",JOptionPane.YES_NO_CANCEL_OPTION);
switch(i)
{
case JOptionPane.YES_OPTION:
return true;
case JOptionPane.NO_OPTION:
return false;
case JOptionPane.CANCEL_OPTION:
return false;
default:
return false;
}
}
//调用文件新建
void FileNew()
{
if(bsaved){
this.jTextArea1.setText("");
this.jTextArea1.setFocusable(true);
this.setTitle("未命名");
this.statubar.setText("新建文本");
}
else FileSaveTo();
}
//调用文件打开
void FileOpen()
{
String strFileOpen="";
if(bsaved){
try{
if(this.jFileChooser.APPROVE_OPTION==this.jFileChooser.showOpenDialog(this)){
strFileOpen=this.jFileChooser.getSelectedFile().getPath();
File file=new File(strFileOpen);
int flength=(int)file.length();
int num=0;
FileReader fReader=new FileReader(file);
char[] data=new char[flength];
while(fReader.ready()){
num+=fReader.read(data,num,flength-num);
}
fReader.close();
jTextArea1.setText(new String(data,0,num));
filename=strFileOpen;
this.setTitle(filename);
statubar.setText("打开:"+filename);
updateFname();
bsaved=false;
}
else
return ;
}catch(Exception e){
statubar.setText("Error Open:"+e.getMessage());
}
}
else
FileSave();
}
//调用保存对话框
boolean FileSave()
{
if(filename==null){
return FileSaveTo();
}
if(!bsaved){
if(filename.length()!=0){
try{
File saveFile=new File(filename);
FileWriter fw=new FileWriter(saveFile);
fw.write(jTextArea1.getText());
fw.close();
statubar.setText("保存文件:"+filename);
bsaved=true;
updateFname();
}catch(Exception e)
{
statubar.setText("保存出错: "+e.getMessage());
}
}
else{
return FileSaveTo();
}
}
return true;
}
//调用另存对话框
boolean FileSaveTo()
{
if(jFileChooser.APPROVE_OPTION==jFileChooser.showSaveDialog(this)){
filename=jFileChooser.getSelectedFile().getPath();
return FileSave();
}
else{
return false;
}
}
//更改标题
void updateFname(){
String str;
if(filename==null){
str="无标题";
}
else{
str=filename;
}
if(!bsaved){
str="记事本"+str;
}
this.setTitle(str);
this.repaint();
}
//文件关闭
void FileClose(){
if(!bsaved){
if(toExit()){
FileSave();
}
else {
System.exit(0);
}
}
else{
System.exit(0);
}
}
//调用编辑
|