由于入学Awt考得较少,所以为加强联系不宜忘记,试写了个简单的保存修改文件的图形程序练习
package texttest.tool;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class SwtWindowTest
{
public static void main(String[] args)
{
new SwtWindow();
}
}
class SwtWindow
{
private Frame f;
private MenuBar mb;
private Menu mu;
private MenuItem openItem;
private MenuItem saveItem;
private MenuItem closeItem;
private TextArea ta;
private File file;
private FileDialog openfd;
private FileDialog savefd;
SwtWindow()
{
init();
}
private void init()
{
f = new Frame("My TextTool");
//f.setLocation(400,300);
//f.setSize(500,400);
f.setBounds(400,300,500,400);
mb = new MenuBar();
mu = new Menu("文件");
openItem = new MenuItem("打开");
saveItem = new MenuItem("保存");
closeItem = new MenuItem("关闭");
ta = new TextArea();
mu.add(openItem);
mu.add(saveItem);
mu.add(closeItem);
mb.add(mu);
f.setMenuBar(mb);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
closeItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openfd = new FileDialog(f,"打开文件",FileDialog.LOAD);
openfd.setVisible(true);
String path = openfd.getDirectory();
String name = openfd.getFile();
if ((path==null) || (name==null))
{
return;
}
ta.setText("");
file = new File(path,name);
try
{
BufferedReader bw = new BufferedReader(new FileReader(file));
String len = null;
while ((len=bw.readLine())!=null)
{
ta.append(len+"\r\n");
}
bw.close();
}
catch (IOException ex)
{
throw new RuntimeException("打开文件错误!");
}
}
});
saveItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (!file.exists())
{
savefd = new FileDialog(f,"保存文件",FileDialog.SAVE);
savefd.setVisible(true);
String path = savefd.getDirectory();
String name = savefd.getFile();
if ((path==null) || (name==null))
{
return;
}
file = new File(path,name);
}
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(ta.getText());
bw.flush();
bw.close();
}
catch (IOException ex)
{
throw new RuntimeException("保存文件错误!");
}
}
});
}
}
|
|