JAVA 运用流编程实现简单的"记事本"功能

一、概要

1.功能介绍

2.实现的思路及步骤代码

3.完整代码

二、功能

运用IO流和Swing实现简单的记事本功能(打开、保存、退出)

三、思路及实现步骤

1.在构造函数中画出操作界面

 1 //创建jta
 2         jta = new JTextArea();
 3         jmb = new JMenuBar();
 4         jml = new JMenu("菜单(M)");
 5         //设置助记符
 6         jml.setMnemonic('M');
 7 
 8         //打开按钮
 9         jmi1 = new JMenuItem("打开", new ImageIcon("edit.gif"));
10         //添加图标的第二种方法
11         //ImageIcon ic = new ImageIcon("edit.gif");
12         //jmi1.setIcon(ic);
13         //保存按钮
14         jmi2 = new JMenuItem("保存");
15         //退出按钮
16         jmi3 = new JMenuItem("退出");
17 
18         //放入控件
19         this.setJMenuBar(jmb);
20         //把JMenu放入到JMenuBar
21         jmb.add(jml);
22         //把item放入到Menu中去
23         jml.add(jmi1);
24         jml.add(jmi2);
25         jml.add(jmi3);
26 
27         //放入到JFrame里
28         this.add(jta);
29         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30         this.setSize(400, 300);
31         this.setVisible(true);
View Code

界面展示:

 

 

2.注册监听事件(判断点了哪个按钮)

 1 //进行注册监听
 2         //打开
 3         jmi1.addActionListener(this);
 4         jmi1.setActionCommand("open");
 5         //保存
 6         jmi2.addActionListener(this);
 7         jmi2.setActionCommand("save");
 8         //退出
 9         jmi3.addActionListener(this);
10         jmi3.setActionCommand("quit");
View Code

 

3.根据事件反馈判断要进行的操作(根据点击的按钮来判断要做什么事)

①打开

 1 if (e.getActionCommand().equals("open")) {
 2             //JFileChooser文件选择组件
 3             JFileChooser jfc1 = new JFileChooser();
 4             //设置名字
 5             jfc1.setDialogTitle("请选择文件...");
 6 
 7             jfc1.showOpenDialog(null);
 8             //显示
 9             jfc1.setVisible(true);
10 
11             String file = null;
12             try {
13                 //得到用户选择的文件绝对(全)路径
14                 file = jfc1.getSelectedFile().getAbsolutePath();
15 
16                 //System.out.println(filename);
17                 FileReader fr = null;
18                 BufferedReader br = null;
19                 try {
20                     fr = new FileReader(file);
21                     br = new BufferedReader(fr);
22                     //从文件中读取信息并显示到jta
23                     String s = "";
24                     String allCon = "";
25                     while ((s = br.readLine()) != null) {
26                         allCon += s + "\r\n";
27                     }
28 
29                     //放置到jta即可
30                     jta.setText(allCon);
31 
32                 } catch (Exception ex) {
33                     ex.printStackTrace();
34                 } finally {
35                     try {
36                         if (br != null && fr != null) {
37                             br.close();
38                             fr.close();
39                         }
40                     } catch (Exception ex) {
41                         ex.printStackTrace();
42                     }
43                 }
44             } catch (Exception ex) {
45                 System.out.println("未选中文件");
46                 //ex.printStackTrace();
47             }
48         }
View Code

②保存

 1 if (e.getActionCommand().equals("save")) {
 2             //出现保存对话框
 3             JFileChooser jfc = new JFileChooser();
 4             jfc.setDialogTitle("另存为...");
 5             //按默认的方式显示
 6             jfc.showSaveDialog(null);
 7             jfc.setVisible(true);
 8 
 9             String file = null;
10             try {
11                 //得到用户希望把文件保存到的地址(文件绝对路径)
12                 file = jfc.getSelectedFile().getAbsolutePath();
13 
14                 //写入到指定文件
15                 FileWriter fw = null;
16                 BufferedWriter bw = null;
17                 try {
18                     fw = new FileWriter(file);
19                     bw = new BufferedWriter(fw);
20 
21                     bw.write(this.jta.getText());
22                 } catch (Exception ex) {
23                     ex.printStackTrace();
24                 } finally {
25                     try {
26                         //bw和fw的关闭顺序不能写反,否则会报错
27                         if (bw != null && fw != null) {
28                             bw.close();
29                             fw.close();
30                         }
31                     } catch (Exception ex) {
32                         ex.printStackTrace();
33                     }
34                 }
35             } catch (Exception ex) {
36                 System.out.println("未选中文件");
37                 //ex.printStackTrace();
38                 //System.out.println(ex.getMessage());
39             }
40         }
View Code

③退出

1 if (e.getActionCommand().equals("quit")) {
2             System.exit(0);
3         }
View Code

 

四、附上完整代码

  1 /**
  2  * 我的记事本(界面+功能)
  3  */
  4 package com.test3;
  5 
  6 import javax.swing.*;
  7 import java.awt.event.*;
  8 import java.io.BufferedReader;
  9 import java.io.BufferedWriter;
 10 import java.io.FileReader;
 11 import java.io.FileWriter;
 12 
 13 public class NotePad extends JFrame implements ActionListener {
 14     //定义需要的组件
 15     JTextArea jta = null;
 16 
 17     //菜单条
 18     JMenuBar jmb = null;
 19 
 20     //定义JMenu(菜单栏按钮)
 21     JMenu jml = null;
 22 
 23     //定义JMenuItem(功能按钮)
 24     JMenuItem jmi1 = null;
 25     JMenuItem jmi2 = null;
 26     JMenuItem jmi3 = null;
 27 
 28     public static void main(String[] args) {
 29         NotePad notePad = new NotePad();
 30     }
 31 
 32     //构造函数
 33     public NotePad() {
 34         //创建jta
 35         jta = new JTextArea();
 36         jmb = new JMenuBar();
 37         jml = new JMenu("菜单(M)");
 38         //设置助记符
 39         jml.setMnemonic('M');
 40 
 41         //打开按钮
 42         jmi1 = new JMenuItem("打开", new ImageIcon("edit.gif"));
 43         //添加图标的第二种方法
 44         //ImageIcon ic = new ImageIcon("edit.gif");
 45         //jmi1.setIcon(ic);
 46         //保存按钮
 47         jmi2 = new JMenuItem("保存");
 48         //退出按钮
 49         jmi3 = new JMenuItem("退出");
 50 
 51         Listen();
 52 
 53         //放入控件
 54         this.setJMenuBar(jmb);
 55         //把JMenu放入到JMenuBar
 56         jmb.add(jml);
 57         //把item放入到Menu中去
 58         jml.add(jmi1);
 59         jml.add(jmi2);
 60         jml.add(jmi3);
 61 
 62         //放入到JFrame里
 63         this.add(jta);
 64         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 65         this.setSize(400, 300);
 66         this.setVisible(true);
 67     }
 68 
 69     //监听事件
 70     public void Listen()
 71     {
 72         //进行注册监听
 73         //打开
 74         jmi1.addActionListener(this);
 75         jmi1.setActionCommand("open");
 76         //保存
 77         jmi2.addActionListener(this);
 78         jmi2.setActionCommand("save");
 79         //退出
 80         jmi3.addActionListener(this);
 81         jmi3.setActionCommand("quit");
 82     }
 83 
 84     @Override
 85     public void actionPerformed(ActionEvent e) {
 86         //判断触发了哪个功能按钮
 87         //打开
 88         if (e.getActionCommand().equals("open")) {
 89             //JFileChooser文件选择组件
 90             JFileChooser jfc1 = new JFileChooser();
 91             //设置名字
 92             jfc1.setDialogTitle("请选择文件...");
 93 
 94             jfc1.showOpenDialog(null);
 95             //显示
 96             jfc1.setVisible(true);
 97 
 98             String file = null;
 99             try {
100                 //得到用户选择的文件绝对(全)路径
101                 file = jfc1.getSelectedFile().getAbsolutePath();
102 
103                 //System.out.println(filename);
104                 FileReader fr = null;
105                 BufferedReader br = null;
106                 try {
107                     fr = new FileReader(file);
108                     br = new BufferedReader(fr);
109                     //从文件中读取信息并显示到jta
110                     String s = "";
111                     String allCon = "";
112                     while ((s = br.readLine()) != null) {
113                         allCon += s + "\r\n";
114                     }
115 
116                     //放置到jta即可
117                     jta.setText(allCon);
118 
119                 } catch (Exception ex) {
120                     ex.printStackTrace();
121                 } finally {
122                     try {
123                         if (br != null && fr != null) {
124                             br.close();
125                             fr.close();
126                         }
127                     } catch (Exception ex) {
128                         ex.printStackTrace();
129                     }
130                 }
131             } catch (Exception ex) {
132                 System.out.println("未选中文件");
133                 //ex.printStackTrace();
134             }
135         }
136         //保存
137         else if (e.getActionCommand().equals("save")) {
138             //出现保存对话框
139             JFileChooser jfc = new JFileChooser();
140             jfc.setDialogTitle("另存为...");
141             //按默认的方式显示
142             jfc.showSaveDialog(null);
143             jfc.setVisible(true);
144 
145             String file = null;
146             try {
147                 //得到用户希望把文件保存到的地址(文件绝对路径)
148                 file = jfc.getSelectedFile().getAbsolutePath();
149 
150                 //写入到指定文件
151                 FileWriter fw = null;
152                 BufferedWriter bw = null;
153                 try {
154                     fw = new FileWriter(file);
155                     bw = new BufferedWriter(fw);
156 
157                     bw.write(this.jta.getText());
158                 } catch (Exception ex) {
159                     ex.printStackTrace();
160                 } finally {
161                     try {
162                         //bw和fw的关闭顺序不能写反,否则会报错
163                         if (bw != null && fw != null) {
164                             bw.close();
165                             fw.close();
166                         }
167                     } catch (Exception ex) {
168                         ex.printStackTrace();
169                     }
170                 }
171             } catch (Exception ex) {
172                 System.out.println("未选中文件");
173                 //ex.printStackTrace();
174                 //System.out.println(ex.getMessage());
175             }
176         }
177         //退出
178         else if (e.getActionCommand().equals("quit")) {
179             System.exit(0);
180         }
181     }
182 }
View Code

 

转载于:https://www.cnblogs.com/ShaneLiu/p/10836519.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import java.awt.BorderLayout; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; public class JNotePadUI extends JFrame { private JMenuItem menuOpen; private JMenuItem menuSave; private JMenuItem menuSaveAs; private JMenuItem menuClose; private JMenu editMenu; private JMenuItem menuCut; private JMenuItem menuCopy; private JMenuItem menuPaste; private JMenuItem menuAbout; private JTextArea textArea; private JLabel stateBar; private JFileChooser fileChooser; private JPopupMenu popUpMenu; public JNotePadUI() { super("新建文本文件"); setUpUIComponent(); setUpEventListener(); setVisible(true); } private void setUpUIComponent() { setSize(640, 480); // 菜单栏 JMenuBar menuBar = new JMenuBar(); // 设置「文件」菜单 JMenu fileMenu = new JMenu("文件"); menuOpen = new JMenuItem("打开"); // 快捷键设置 menuOpen.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_O, InputEvent.CTRL_MASK)); menuSave = new JMenuItem("保存"); menuSave.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, InputEvent.CTRL_MASK)); menuSaveAs = new JMenuItem("另存为"); menuClose = new JMenuItem("关闭"); menuClose.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, InputEvent.CTRL_MASK)); fileMenu.add(menuOpen); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuSave); fileMenu.add(menuSaveAs); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuClose); // 设置「编辑」菜单 JMenu editMenu = new JMenu("编辑"); menuCut = new JMenuItem("剪切"); menuCut.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK)); menuCopy = new JMenuItem("复制"); menuCopy.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); menuPaste = new JMenuItem("粘贴"); menuPaste.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); editMenu.add(menuCut); editMenu.add(menuCopy); editMenu.add(menuPaste); // 设置「关于」菜单 JMenu aboutMenu = new JMenu("关于"); menuAbout = new JMenuItem("关于JNotePad"); aboutMenu.add(menuAbout); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); setJMenuBar(menuBar); // 文字编辑区域 textArea = new JTextArea(); textArea.setFont(new Font("宋体", Font.PLAIN, 16)); textArea.setLineWrap(true); JScrollPane panel = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); // 状态栏 stateBar = new JLabel("未修改"); stateBar.setHorizontalAlignment(SwingConstants.LEFT); stateBar.setBorder( BorderFactory.createEtchedBorder()); contentPane.add(stateBar, BorderLayout.SOUTH); popUpMenu = editMenu.getPopupMenu(); fileChooser = new JFileChooser(); } private void setUpEventListener() { // 按下窗口关闭钮事件处理 addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { closeFile(); } } ); // 菜单 - 打开 menuOpen.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } } ); // 菜单 - 保存 menuSave.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFile(); } } ); // 菜单 - 另存为 menuSaveAs.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFileAs(); } } ); // 菜单 - 关闭文件 menuClose.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { closeFile(); } } ); // 菜单 - 剪切 menuCut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cut(); } } ); // 菜单 - 复制 menuCopy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { copy(); } } ); // 菜单 - 粘贴 menuPaste.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { paste(); } } ); // 菜单 - 关于 menuAbout.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // 显示对话框 JOptionPane.showOptionDialog(null, "程序名称:\n JNotePad \n" + "程序设计:\n \n" + "简介:\n 一个简单的文字编辑器\n" + " 可作为验收Java实现对象\n" + " 欢迎网友下载研究交\n\n" + " /", "关于JNotePad", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); } } ); // 编辑区键盘事件 textArea.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { processTextArea(); } } ); // 编辑区鼠标事件 textArea.addMouseListener( new MouseAdapter() { public void mouseReleased(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3) popUpMenu.show(editMenu, e.getX(), e.getY()); } public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) popUpMenu.setVisible(false); } } ); } private void openFile() { if(isCurrentFileSaved()) { // 文件是否为保存状态 open(); // 打开 } else { // 显示对话框 int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { // 确认文件保存 case JOptionPane.YES_OPTION: saveFile(); // 保存文件 break; // 放弃文件保存 case JOptionPane.NO_OPTION: open(); break; } } } private boolean isCurrentFileSaved() { if(stateBar.getText().equals("未修改")) { return false; } else { return true; } } private void open() { // fileChooser 是 JFileChooser 的实例 // 显示文件选取的对话框 int option = fileChooser.showDialog(null, null); // 使用者按下确认键 if(option == JFileChooser.APPROVE_OPTION) { try { // 开启选取的文件 BufferedReader buf = new BufferedReader( new FileReader( fileChooser.getSelectedFile())); // 设定文件标题 setTitle(fileChooser.getSelectedFile().toString()); // 清除前一次文件 textArea.setText(""); // 设定状态栏 stateBar.setText("未修改"); // 取得系统相依的换行字符 String lineSeparator = System.getProperty("line.separator"); // 读取文件并附加至文字编辑区 String text; while((text = buf.readLine()) != null) { textArea.append(text); textArea.append(lineSeparator); } buf.close(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "开启文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFile() { // 从标题栏取得文件名称 File file = new File(getTitle()); // 若指定的文件不存在 if(!file.exists()) { // 执行另存为 saveFileAs(); } else { try { // 开启指定的文件 BufferedWriter buf = new BufferedWriter( new FileWriter(file)); // 将文字编辑区的文字写入文件 buf.write(textArea.getText()); buf.close(); // 设定状态栏为未修改 stateBar.setText("未修改"); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "写入文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFileAs() { // 显示文件对话框 int option = fileChooser.showSaveDialog(null); // 如果确认选取文件 if(option == JFileChooser.APPROVE_OPTION) { // 取得选择的文件 File file = fileChooser.getSelectedFile(); // 在标题栏上设定文件名称 setTitle(file.toString()); try { // 建立文件 file.createNewFile(); // 进行文件保存 saveFile(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "无法建立新文件", JOptionPane.ERROR_MESSAGE); } } } private void closeFile() { // 是否已保存文件 if(isCurrentFileSaved()) { // 释放窗口资源,而后关闭程序 dispose(); } else { int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { case JOptionPane.YES_OPTION: saveFile(); break; case JOptionPane.NO_OPTION: dispose(); } } } private void cut() { textArea.cut(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void copy() { textArea.copy(); popUpMenu.setVisible(false); } private void paste() { textArea.paste(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void processTextArea() { stateBar.setText("已修改"); } public static void main(String[] args) { new JNotePadUI(); } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值