/*
打开文件
*/
package gui6;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class GUIDemo6
{
private Frame f;
private MenuBar mb;
private Menu fileMenu;
private MenuItem openItem;
private MenuItem saveItem;
private MenuItem closeItem;
private FileDialog openDialog;
private FileDialog saveDialog;
private TextArea ta;
private File file;
GUIDemo6()
{
init();
}
//初始化组件
public void init()
{
f=new Frame("窗口");
mb=new MenuBar();
fileMenu=new Menu("文件");
openItem=new MenuItem("打开");
saveItem=new MenuItem("保存");
closeItem=new MenuItem("退出");
ta=new TextArea();
openDialog=new FileDialog(f,"openFile",FileDialog.LOAD);
saveDialog=new FileDialog(f,"saveFile",FileDialog.SAVE);
f.setBounds(300,200,600,500);
f.setMenuBar(mb);
mb.add(fileMenu);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
f.add(ta);
myEvent();
f.setVisible(true);
}
//监听事件
public void myEvent()
{
//保存监听事件
saveItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(file==null)
{
saveDialog.setVisible(true);
String dir=saveDialog.getDirectory();
String fileName=saveDialog.getFile();
if(dir==null || fileName==null)
return;
file=new File(dir,fileName);
}
BufferedWriter bufw=null;
try
{
bufw=new BufferedWriter(new FileWriter(file));
String text=ta.getText();
System.out.println(text);
bufw.write(text);
bufw.flush();
}
catch (IOException exce)
{
throw new RuntimeException("写入失败");
}
finally
{
try
{
if(bufw!=null)
bufw.close();
}
catch (IOException excep)
{
}
}
}
});
//打开监听事件
openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openDialog.setVisible(true);
String dir=openDialog.getDirectory();
String fileName=openDialog.getFile();
if(dir==null || fileName==null)
return;
else
{
BufferedReader bufr=null;
try
{
ta.setText("");
File file=new File(dir,fileName);
FileReader fr=new FileReader(file);
bufr=new BufferedReader(fr);
String line=null;
while((line=bufr.readLine())!=null)
{
ta .append(line+"\r\n");
}
}
catch (IOException exc)
{
}
finally
{
try
{
if(bufr!=null)
bufr.close();
}
catch (IOException ex)
{
}
}
}
}
});
}
public static void main(String[] args)
{
new GUIDemo6();
}
}
GUI(打开、保存文件)
最新推荐文章于 2023-08-02 10:38:57 发布