一个记事本程序

一个记事本程序,先建立一个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, "无法读文件,请检查文件是否被锁定");
				}
			}
		}
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,我可以回答这个问题。使用wxPython编写记事本程序可以通过以下步骤实现: 1. 导入wxPython模块 2. 创建一个应用程序对象 3. 创建一个顶级窗口对象 4. 在窗口对象中添加文本框控件 5. 在窗口对象中添加菜单栏和工具栏 6. 实现菜单栏和工具栏的功能,例如打开、保存、剪切、复制、粘贴等 7. 运行应用程序 以上是大致的步骤,具体实现可以参考wxPython的官方文档和示例代码。 ### 回答2: 用wxPython编写一个记事本程序可以实现基本的文本编辑功能。首先,我们需要导入wxPython模块,并创建一个应用程序对象和一个顶层窗口对象。然后,在窗口对象中添加一个多行文本框作为编辑区域,并设置其样式和布局。接下来,我们可以添加菜单栏和工具栏来增加一些功能按钮,如新建、打开、保存、剪切、复制、粘贴等等。通过绑定事件处理函数,我们可以实现这些按钮的功能。 例如,当点击新建按钮时,我们可以清空文本框中的内容;当点击打开按钮时,可以弹出文件选择对话框,选择要打开的文件并将其内容显示在文本框中;当点击保存按钮时,可以弹出保存文件对话框,将文本框中的内容保存到指定的文件中。 除了基本的编辑功能,我们还可以通过wxPython提供的丰富控件库来增加其他功能,如查找和替换、字体和颜色设置、撤销和重做等等。 总之,使用wxPython编写记事本程序可以使我们能够方便地创建一个简单的文本编辑工具,通过定制和扩展,我们还可以实现更多更高级的功能。 ### 回答3: 使用wxPython编写一个记事本程序,首先需要导入wxPython模块。然后创建一个wx.App()实例来启动程序。 接下来,创建一个wx.Frame()实例作为主窗口。在主窗口中,可以添加一个wx.TextCtrl()组件作为文本输入框,用来输入和编辑文字内容。还可以添加一个菜单栏和工具栏,用来实现一些额外的功能比如打开、保存文件,设置字体、样式等。 在编写记事本程序时,可以定义相应的事件处理函数来实现功能。比如,可以为菜单栏和工具栏上的“打开”按钮绑定一个事件处理函数,当用户点击这个按钮时,就会触发这个函数,从而实现打开文件的功能。类似地,可以为保存按钮绑定一个事件处理函数,实现保存文件的功能。 此外,还可以添加一些其他的功能,比如设置字体样式、查找和替换文本、撤销和重做操作等。可以通过定义相应的事件处理函数来监听用户的操作,实现这些功能。 最后,调用wx.App().MainLoop()来进入主事件循环,使程序能够响应用户的操作,并持续运行。 这个记事本程序使用wxPython编写,可以在图形界面下方便地输入和编辑文字内容,并提供了一些常用的功能如打开、保存文件,设置字体样式等。可以根据实际需求,进一步扩展和优化这个记事本程序

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值