import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.swing.JFrame;
public class MyNotePad {
/**
* @param args
*/
public static void main(String[] args) {
final JFrame note = new JFrame("记事本");
note.setSize(400, 500);
final TextArea text = new TextArea();
text.setFont(new Font("华文楷体", Font.BOLD, 18));
MenuBar bar = new MenuBar();
Menu file = new Menu("文件(F)");
Menu edit = new Menu("编辑(E)");
Menu format=new Menu("格式(O)");
Menu viw=new Menu("查看(V)");
Menu help=new Menu("帮助(H)");
MenuItem open = new MenuItem("打开");
MenuItem save = new MenuItem("保存");
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileDialog dialog = new FileDialog(note, "保存", FileDialog.SAVE);
dialog.setVisible(true);
File file = new File(dialog.getDirectory(), dialog.getFile());
try {
@SuppressWarnings("resource")
FileOutputStream savefile = new FileOutputStream(file);
String saveString=text.getText();
savefile.write(saveString.getBytes());
savefile.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
MenuItem newfile = new MenuItem("新建");
open.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileDialog dialog = new FileDialog(note, "打开");
dialog.setVisible(true);
File f = new File(dialog.getDirectory(), dialog.getFile());
try {
@SuppressWarnings("resource")
FileInputStream openfile = new FileInputStream(f);
byte[] b = new byte[1024 * 8];
int len = 0;
while ((len = openfile.read(b)) != -1) {
text.append(new String(b, 0, len));
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
file.add(newfile);
file.add(open);
file.add(save);
bar.add(file);
bar.add(edit);
bar.add(format);
bar.add(viw);
bar.add(help);
text.setBackground(new Color(199, 237, 204));
note.setMenuBar(bar);
note.add(text);
note.setLocationRelativeTo(null);
note.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
note.setVisible(true);
}
}
|
|