【swing】简单记事本的开发

来源:互联网 发布:linux安装lnmp 编辑:程序博客网 时间:2024/05/19 14:16

1、运行截图


2、源码:

package jframe;import java.awt.Color;import java.awt.Dimension;import java.awt.EventQueue;import java.awt.Font;import java.awt.GraphicsEnvironment;import java.awt.Insets;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import javax.swing.JCheckBoxMenuItem;import javax.swing.JColorChooser;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;import javax.swing.undo.UndoManager;/** * swing 简单记事本 * @author kissy小强 * */public class Note extends JFrame {private static final long serialVersionUID = 1L;UndoManager manager = new UndoManager();JTextArea text = new JTextArea();JFileChooser chooser;String s = "新建记事本";int result = 0;private File file;JMenuBar Mb;JMenu M1, M2, M3, M4;JMenuItem m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m32, m33, m41;private final static int HEIGHT=450;      private final static int WIDTH=750;      JCheckBoxMenuItem m31 = new JCheckBoxMenuItem("自动换行", true);    public static void main(String args[]) {    String lookAndFeel = UIManager.getSystemLookAndFeelClassName();    try {UIManager.setLookAndFeel(lookAndFeel);} catch (ClassNotFoundException | InstantiationException| IllegalAccessException | UnsupportedLookAndFeelException e1) {e1.printStackTrace();}EventQueue.invokeLater(new Runnable() {public void run() {try {Note n = new Note();} catch (Exception e) {e.printStackTrace();}}});}    public Note() {setTitle(s);setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();// 离显示屏上边缘x像素,里显示屏左边缘y像素setLocation(screenSize.width / 2 - WIDTH / 2, screenSize.height / 2- HEIGHT / 2);setSize(WIDTH, HEIGHT);setResizable(true); // 窗体是否可变setVisible(true); // 窗体是否可见init();}private void init(){Mb = new JMenuBar();this.setJMenuBar(Mb);text.getDocument().addUndoableEditListener(manager);// 设置文本框编辑监听(可撤销)text.setFont(new Font("宋体", Font.PLAIN, 14));text.setCaretColor(Color.RED);// 光标颜色text.setSelectedTextColor(Color.RED);// 选中字体颜色text.setSelectionColor(Color.GREEN);// 选中背景颜色text.setLineWrap(true); // 是否换行text.setWrapStyleWord(true); // 是否单词边界换行(即有空白)text.setMargin(new Insets(3, 5, 3, 5));// 文本区与边框的间距,四个参数分别为上、左、下、右text.setDragEnabled(true); // 开启或关闭自动拖动处理add(new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));M1 = this.AddBar("文件", Mb);M2 = this.AddBar("编辑", Mb);M3 = this.AddBar("格式", Mb);M4 = this.AddBar("帮助", Mb);/* 新建选项 */m11 = this.AddItem("新建", M1);m11.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {text.setText("");setTitle(s);file = null;}});/* 打开选项 */m12 = this.AddItem("打开", M1);m12.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {try {// 设置打开时的默认目录,两种方式chooser = new JFileChooser("C:\\Users\\xiaozhx\\Desktop");// chooser.setCurrentDirectory(new File("C:\\Users\\xiaozhx\\Desktop"));chooser.setFileFilter(new filter());result = chooser.showOpenDialog(null);if (result == JFileChooser.APPROVE_OPTION) {// 点击了打开按钮file = chooser.getSelectedFile();int length = (int) file.length();FileReader reader = new FileReader(file);char[] ch = new char[length];reader.read(ch);reader.close();text.setText(new String(ch).trim());setTitle(file.getName());} else if (result == JFileChooser.CANCEL_OPTION) {// 点击了取消按钮}} catch (Exception e) {JOptionPane.showMessageDialog(null, e);}}});/* 保存选项 */m13 = this.AddItem("保存", M1);m13.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {if (file == null)try {chooser = new JFileChooser("C:\\Users\\xiaozhx\\Desktop");chooser.setFileFilter(new filter());result = chooser.showSaveDialog(null);if (result == JFileChooser.APPROVE_OPTION) {File selectfile = chooser.getSelectedFile(); // 获得文件名// 获得被选中的过滤器中的文件扩展名String end = chooser.getFileFilter().getDescription();File newFile = null;if (selectfile.getAbsolutePath().toUpperCase().endsWith(end.toUpperCase())) {// 如果文件是以选定扩展名结束的,则使用原名newFile = selectfile;} else {// 否则加上选定的扩展名newFile = new File(selectfile.getAbsolutePath()+ end);}try {if (newFile.exists() == false) {newFile.createNewFile();}FileWriter writer = new FileWriter(newFile);char[] arry = text.getText().toCharArray();writer.write(arry);writer.flush();writer.close();setTitle(newFile.getName());file = newFile;} catch (IOException e) {}} else if (result == JFileChooser.CANCEL_OPTION) {// 点击了取消按钮}} catch (Exception e) {JOptionPane.showMessageDialog(null, e);}elsetry {FileWriter writer = new FileWriter(file);char[] arry = text.getText().toCharArray();writer.write(arry);writer.flush();writer.close();} catch (Exception e) {JOptionPane.showMessageDialog(null, e);}}});/* 另存为选项 */m14 = this.AddItem("另存为", M1);m14.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {try {chooser = new JFileChooser("C:\\Users\\xiaozhx\\Desktop");chooser.setFileFilter(new filter());result = chooser.showSaveDialog(null);if (result == JFileChooser.APPROVE_OPTION) {File selectfile = chooser.getSelectedFile(); // 获得文件名// 获得被选中的过滤器中的文件扩展名String end = chooser.getFileFilter().getDescription();File newFile = null;if (selectfile.getAbsolutePath().toUpperCase().endsWith(end.toUpperCase())) {// 如果文件是以选定扩展名结束的,则使用原名newFile = selectfile;} else {// 否则加上选定的扩展名newFile = new File(selectfile.getAbsolutePath()+ end);}try {if (newFile.exists() == false) {newFile.createNewFile();}FileWriter writer = new FileWriter(newFile);char[] arry = text.getText().toCharArray();writer.write(arry);writer.flush();writer.close();setTitle(newFile.getName());file = newFile;} catch (IOException e) {}} else if (result == JFileChooser.CANCEL_OPTION) {// 点击了取消按钮}} catch (Exception e) {JOptionPane.showMessageDialog(null, e);}}});M1.addSeparator(); // 横杆/* 退出选项 */m15 = this.AddItem("退出", M1);m15.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {System.exit(0);}});/* 撤消选项 */m21 = this.AddItem("撤消", M2);m21.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {if (manager.canUndo())manager.undo();}});/* 剪切选项 */M2.addSeparator();m22 = this.AddItem("剪切", M2);m22.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {text.cut();}});/* 复制选项 */m23 = this.AddItem("复制", M2);m23.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {text.copy();}});/* 粘贴选项 */m24 = this.AddItem("粘贴", M2);m24.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {text.paste();}});/* 删除选项 */m25 = this.AddItem("删除", M2);m25.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {text.replaceRange("", text.getSelectionStart(),text.getSelectionEnd());}});/* 自动换行选项 */M3.add(m31);m31.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {if (m31.getState())text.setLineWrap(true);elsetext.setLineWrap(false);}});/* 字体格式设置选项 */m32 = this.AddItem("字体选择", M3);m32.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();//获取系统字体JList<String> fontNames = new JList<String>(ge.getAvailableFontFamilyNames());int response = JOptionPane.showConfirmDialog(null,new JScrollPane(fontNames), "请选择字体",JOptionPane.OK_CANCEL_OPTION);Object selectedFont = fontNames.getSelectedValue();if (response == JOptionPane.OK_OPTION && selectedFont != null)text.setFont(new Font(fontNames.getSelectedValue().toString(), Font.PLAIN, 20));}});/* 字体颜色设置选项 */m33 = this.AddItem("字体颜色", M3);m33.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {Color color = JColorChooser.showDialog(null, "文字颜色选择",Color.WHITE);text.setForeground(color);}});m41 = this.AddItem("关于记事本", M4);m41.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {JOptionPane.showMessageDialog(null, "记事本\n开发语言:JAVA\n开发者:袁健强","关于", JOptionPane.PLAIN_MESSAGE);}});}/** 文件格式过滤器 **/private class filter extends javax.swing.filechooser.FileFilter {public boolean accept(File file) {String name = file.getName();name.toLowerCase();if (name.endsWith(".txt") || file.isDirectory())return true;elsereturn false;}public String getDescription() {return ".txt";}}/** 将菜单项JMenuItem添加到菜单JMenu **/public JMenuItem AddItem(String name, JMenu menu) {JMenuItem MI = new JMenuItem(name);menu.add(MI);return MI;}/** 将菜单JMenu添加到菜栏JMenuBar **/public JMenu AddBar(String name, JMenuBar mb) {JMenu Mb = new JMenu(name);mb.add(Mb);return Mb;}}


1 0
原创粉丝点击