一个记事本程序,先建立一个java项目,然后再src下建立一个包名为:com.txt.notebook,然后新建俩个类,完整代码如下:
package com.txt.notebook;
import java.io.File;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.filechooser.*;
public class ExampleFileFilter extends FileFilter {
private static String TYPE_UNKNOWN = "Type Unknown";
private static String HIDDEN_FILE = "Hidden File";
private Hashtable filters = null;
private String description = null;
private String fullDescription = null;
private boolean useExtensionsInDescription = true;
/**
* Creates a file filter. If no filters are added, then all files are
* accepted.
*
* @see #addExtension
*/
public ExampleFileFilter() {
this.filters = new Hashtable();
}
/**
* Creates a file filter that accepts files with the given extension.
* Example: new ExampleFileFilter("jpg");
*
* @see #addExtension
*/
public ExampleFileFilter(String extension) {
this(extension, null);
}
/**
* Creates a file filter that accepts the given file type. Example: new
* ExampleFileFilter("jpg", "JPEG Image Images");
*
* Note that the "." before the extension is not needed. If provided, it
* will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String extension, String description) {
this();
if (extension != null)
addExtension(extension);
if (description != null)
setDescription(description);
}
/**
* Creates a file filter from the given string array. Example: new
* ExampleFileFilter(String {"gif", "jpg"});
*
* Note that the "." before the extension is not needed adn will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String[] filters) {
this(filters, null);
}
/**
* Creates a file filter from the given string array and description.
* Example: new ExampleFileFilter(String {"gif", "jpg"},
* "Gif and JPG Images");
*
* Note that the "." before the extension is not needed and will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String[] filters, String description) {
this();
for (int i = 0; i < filters.length; i++) {
// add filters one by one
addExtension(filters[i]);
}
if (description != null)
setDescription(description);
}
/**
* Return true if this file should be shown in the directory pane, false if
* it shouldn't.
*
* Files that begin with "." are ignored.
*
* @see #getExtension
* @see FileFilter#accepts
*/
public boolean accept(File f) {
if (f != null) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null && filters.get(getExtension(f)) != null) {
return true;
}
;
}
return false;
}
/**
* Return the extension portion of the file's name .
*
* @see #getExtension
* @see FileFilter#accept
*/
public String getExtension(File f) {
if (f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if (i > 0 && i < filename.length() - 1) {
return filename.substring(i + 1).toLowerCase();
}
;
}
return null;
}
/**
* Adds a filetype "dot" extension to filter against.
*
* For example: the following code will create a filter that filters out all
* files except those that end in ".jpg" and ".tif":
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("jpg"); filter.addExtension("tif");
*
* Note that the "." before the extension is not needed and will be ignored.
*/
public void addExtension(String extension) {
if (filters == null) {
filters = new Hashtable(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
/**
* Returns the human readable description of this filter. For example:
* "JPEG and GIF Image Files (*.jpg, *.gif)"
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
* @see FileFilter#getDescription
*/
public String getDescription() {
if (fullDescription == null) {
if (description == null || isExtensionListInDescription()) {
fullDescription = description == null ? "(" : description
+ " (";
// build the description from the extension list
Enumeration extensions = filters.keys();
if (extensions != null) {
fullDescription += "." + (String) extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", "
+ (String) extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
}
/**
* Sets the human readable description of this filter. For example:
* filter.setDescription("Gif and JPG Images");
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
*/
public void setDescription(String description) {
this.description = description;
fullDescription = null;
}
/**
* Determines whether the extension list (.jpg, .gif, etc) should show up in
* the human readable description.
*
* Only relevent if a description was provided in the constructor or using
* setDescription();
*
* @see getDescription
* @see setDescription
* @see isExtensionListInDescription
*/
public void setExtensionListInDescription(boolean b) {
useExtensionsInDescription = b;
fullDescription = null;
}
/**
* Returns whether the extension list (.jpg, .gif, etc) should show up in
* the human readable description.
*
* Only relevent if a description was provided in the constructor or using
* setDescription();
*
* @see getDescription
* @see setDescription
* @see setExtensionListInDescription
*/
public boolean isExtensionListInDescription() {
return useExtensionsInDescription;
}
}
package com.txt.notebook;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.event.*;
import javax.print.*;
import javax.print.attribute.*;
import java.util.*;
import java.text.*;
/**
* MyNotebook 示例
*/
public class MyNotebook extends JFrame implements ActionListener {
Container con;
JScrollPane JSPane;
JTextArea text;
JMenuBar mainMenuBar;
JMenu fileMenu, editMenu, formatMenu, helpMenu;
JMenuItem newItem, openItem, saveItem, saveasItem, pageItem, printItem,
exitItem;
JMenuItem undoItem, cutItem, copyItem, pasteItem, findItem, replaceItem,
selectallItem, dateItem;
JCheckBoxMenuItem wrapItem;
JMenuItem fontItem;
JMenuItem helpItem, aboutItem;
boolean changed = false;
boolean haveName = false;
File file = null;
// 主程序入口
public static void main(String[] args) {
MyNotebook notbook = new MyNotebook();
notbook.setVisible(true);
}
// 创建界面、安装各种监听器、
public MyNotebook() {
setTitle("记事本 -- 未命名");
con = getContentPane();
text = new JTextArea();
JSPane = new JScrollPane(text);
createMenu();
setJMenuBar(mainMenuBar);
con.add(JSPane, BorderLayout.CENTER);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
.getScreenSize();
setBounds((screenSize.width - 800) / 2, (screenSize.height - 600) / 2,
800, 600);
}
// 创建主菜单
public void createMenu() {
// 创建JMenuBar
mainMenuBar = new JMenuBar();
// 创建四个JMenu
fileMenu = new JMenu("文件");
editMenu = new JMenu("编辑");
formatMenu = new JMenu("格式");
helpMenu = new JMenu("帮助");
// 创建JMenuItem并添加到对应的JMenu中
mainMenuBar.add(fileMenu);
newItem = new JMenuItem("新建");
openItem = new JMenuItem("打开..");
saveItem = new JMenuItem("保存..");
saveasItem = new JMenuItem("另存为..");
pageItem = new JMenuItem("页面设置..");
printItem = new JMenuItem("打印..");
exitItem = new JMenuItem("退出");
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(saveasItem);
fileMenu.addSeparator();
fileMenu.add(pageItem);
fileMenu.add(printItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
mainMenuBar.add(helpMenu);
helpItem = new JMenuItem("帮助主题");
aboutItem = new JMenuItem("关于..");
helpMenu.add(helpItem);
helpMenu.add(aboutItem);
exitItem.addActionListener(this);
saveItem.addActionListener(this);
saveasItem.addActionListener(this);
newItem.addActionListener(this);
printItem.addActionListener(this);
openItem.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object obj;
obj = e.getSource();
if (obj == exitItem) {
doExit();
} else if (obj == saveItem) {
doSave();
} else if (obj == saveasItem) {
doSaveAs();
} else if (obj == newItem) {
doNewFile();
} else if (obj == openItem) {
doOpen();
}
}
// 当用户按下窗口的“关闭”时,会自动调用此方法
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
doExit();
}
}
// 程序退出时的代码
void doExit() {
int select;
if (!changed) {
System.exit(0);
} else {
select = JOptionPane.showConfirmDialog(this, "文件修改后尚未存盘,要保存吗?");
switch (select) {
case JOptionPane.YES_OPTION:
select = doSave();
if (select == 1) {
System.exit(0);
}
break;
case JOptionPane.NO_OPTION:
System.exit(0);
break;
case JOptionPane.CANCEL_OPTION:
break;
}
}
}
// 保存用户编辑的文件,保存成功返回1,否则返回0
int doSave() {
FileOutputStream fout;
byte content[];
int flag;
if (!haveName) {
flag = doSaveAs();
} else if (changed) {
try {
fout = new FileOutputStream(file);
content = text.getText().getBytes();
fout.write(content);
fout.close();
changed = false;
JOptionPane.showMessageDialog(this, "保存成功!");
flag = 1;
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "指定的文件名称或属性有问题!");
flag = 0;
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "无法写文件,请检查文件是否被锁定");
flag = 0;
}
} else {
JOptionPane.showMessageDialog(this, "保存成功,其他情况!");
flag = 1;
}
return flag;
}
// 用"另存为"对话框保存文件。保存成功返回1,否则返回0
int doSaveAs() {
FileOutputStream fout;
byte content[];
int flag = 0;
File tmpfile = null;
ExampleFileFilter filter = new ExampleFileFilter();
JFileChooser chooser;
filter.addExtension("txt");
filter.setDescription("文本文件");
if (file != null) {
chooser = new JFileChooser(file.getPath());
} else {
chooser = new JFileChooser();
}
chooser.setFileFilter(filter);
flag = chooser.showSaveDialog(this);
if (flag == JFileChooser.APPROVE_OPTION) {
tmpfile = chooser.getSelectedFile();
if (tmpfile.exists()) {
if (JOptionPane.showConfirmDialog(this, "文件已经存在,是否覆盖?", "警告",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
flag = 1;
} else {
flag = 0;
}
} else {
flag = 1;
}
} else {
flag = 0;
}
if (flag == 1) {// 用户已经确定要以指定名称保存文件
try {
fout = new FileOutputStream(tmpfile);
content = text.getText().getBytes();
fout.write(content);
fout.close();
flag = 1;
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "指定的文件名称或属性有问题!");
flag = 0;
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "无法写文件,请检查文件是否被锁定");
flag = 0;
}
}
if (flag == 1) {// 文件保存成功,修改相关变量
changed = false;
haveName = true;
file = tmpfile;
this.setTitle(file.getName() + " - 记事本");
}
return flag;
}
// 新建一个文件
void doNewFile() {
int select, flag;
if (changed) {
select = JOptionPane.showConfirmDialog(this, "文件修改后尚未存盘,要保存吗?");
switch (select) {
case JOptionPane.YES_OPTION:
flag = doSave();
break;
case JOptionPane.NO_OPTION:
flag = 1;
break;
default:
flag = 0;
break;
}
} else {
flag = 1;
}
if (flag == 1) {
changed = false;
haveName = false;
setTitle("记事本 -- 未命名");
text.setText(null);
}
}
// 打开一个已经存在的文件
void doOpen() {
int select, flag;
File tmpfile = null;
ExampleFileFilter filter;
JFileChooser chooser;
FileInputStream fin;
byte buf[];
if (changed) {
select = JOptionPane.showConfirmDialog(this, "文件修改后尚未存盘,要保存吗?");
switch (select) {
case JOptionPane.YES_OPTION:
flag = doSave();
break;
case JOptionPane.NO_OPTION:
flag = 1;
break;
default:
flag = 0;
break;
}
} else {
flag = 1;
}
if (flag == 1) {
changed = false;
filter = new ExampleFileFilter();
filter.addExtension("txt");
filter.setDescription("文本文件");
if (file != null) {
chooser = new JFileChooser(file.getPath());
} else {
chooser = new JFileChooser();
}
chooser.setFileFilter(filter);
select = chooser.showOpenDialog(this);
if (select == JFileChooser.APPROVE_OPTION) {
tmpfile = chooser.getSelectedFile();
try {
fin = new FileInputStream(tmpfile);
buf = new byte[(int) tmpfile.length()];
fin.read(buf);
fin.close();
text.setText(new String(buf));
changed = false;
haveName = true;
file = tmpfile;
setTitle("记事本 -- " + file.getName());
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "指定的文件名称或属性有问题!");
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "无法读文件,请检查文件是否被锁定");
}
}
}
}
}