这里我只展示最基础的功能,其他功能类似,根据自己需求添加。
该记事本的功能:
1.有菜单条
2.菜单条可以包含很多菜单,我这里只弄了一个“文件”菜单,你们也可以弄编辑之类的菜单。
3.“文件”菜单下有子菜单,我这里是打开和保存。
下面开始实现:
记事本界面用JFrame写出来,如果这都不知道还是先去学会JFrame再做吧。我们知道,要想让计算机对点击记事本做出反应,那么必定离不开监听机制,如果没学过的话,学完再来javascript:void(0)。记事本中的“打开”按钮具体实现打开功能主要用了一个JFileChooser组件,该组件可以让用户选择路径,保存功能也是用该组件,有了路径之后,根据io流的知识可以完成该功能,io流在我博客分类java_demo里面有,其他需要学习的内容我java_demo里面都多多少少会有涉及,可以参考。具体代码里面有注释,其他的我就不多说了。具体实现完了的功能是这样的。
点击打开后:
点击 堆排序.cpp 后:
打开d盘下的a.txt文件后
随便加点内容并保存到d盘,命名为m.txt
打开d盘查看m.txt文件
已经存进去了,换行可以加个\r\n,即
bw.write(this.jta.getText()+"\r\n");
完成打开和保存的功能。
代码如下:
package com.test10;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class NotePad extends JFrame implements ActionListener {
//创建菜单条和菜单以及菜单内容
JTextArea jta = null;
JMenuBar jmb = null;
JMenu jm1 = null;
JMenuItem jmi1 = null;
JMenuItem jmi2 = null;
public static void main(String [] args){
NotePad np = new NotePad();
}
public NotePad(){
//创建对象
jta = new JTextArea();
jmb = new JMenuBar();
jm1 = new JMenu("文件");
jmi1 = new JMenuItem("打开");
jmi2 = new JMenuItem("保存");
//设置助记符
jm1.setMnemonic('F');
//注册监听
jmi1.addActionListener(this);
jmi2.addActionListener(this);
jmi1.setActionCommand("open");
jmi2.setActionCommand("save");
//加入
jm1.add(jmi1);
jm1.add(jmi2);
jmb.add(jm1);
this.setJMenuBar(jmb);
this.add(jta);
//设置JPanel
this.setVisible(true);
this.setSize(400,300);
this.setLocation(500,250);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("open")){
//System.out.println("open");
//设置文件选择组件
JFileChooser jfc1 = new JFileChooser();
//设置名字
jfc1.setDialogTitle("请选择文件...");
//设置默认方式
jfc1.showOpenDialog(null);
//显示
jfc1.setVisible(true);
//得到用户选择的文件绝对路径
String path1 = jfc1.getSelectedFile().getAbsolutePath();
System.out.println(path1);
//创建输入流
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(path1);
br = new BufferedReader(fr);
//从文件中读取信息并显示到记事本的jta中
String s = "";
String str = "";
while((s=br.readLine())!=null){
str += s+"\r\n";
}
//将str(即文件中的内容)放置到jta中
jta.setText(str);
} catch (Exception e1) {
e1.printStackTrace();
} finally {
//关闭输入流
try {
fr.close();
br.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
else if(e.getActionCommand().equals("save")){
//操作与打开相似
JFileChooser jfc2 = new JFileChooser();
jfc2.setDialogTitle("请选择保存路径");
jfc2.showSaveDialog(null);
jfc2.setVisible(true);
String path2 = jfc2.getSelectedFile().getAbsolutePath();
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(path2);
bw = new BufferedWriter(fw);
// String s = "";
// String str = "";
//while((s=))
bw.write(this.jta.getText()+"\r\n");
} catch (Exception e1) {
e1.printStackTrace();
} finally {
try {
bw.close();
fw.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
}