总共两个类,一个程序主界面,一个测试类(包含main函数,实列化程序主界面类)这个是程序主界面的类。package study.com.notebook;import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.JButton;
import javax.swing.JEditorPane;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.StyleConstants;class MainForm extends JFrame implements ActionListener, DocumentListener {
/**
*
*/
private static final long serialVersionUID = 1L;
// 界面元素变量
JMenuBar menuBar; // 菜单
JPanel panel;
JEditorPane textEdit;
JLabel statusLabel; // 控制变量
boolean TextChangeNoSave; // 当前文档的改变是否已经保存
boolean DocIsNew; // 当前文档是否为新建 // 当前文件名次、路径
String filePath;
String fileName; // 系统粘贴板
Clipboard clip; public MainForm() {
// 界面初始化
InitGUI();
InitPara();
} // 界面初始化
public void InitGUI() {
// 菜单栏初始化
menuBar = new JMenuBar();
menuBar.setBackground(Color.LIGHT_GRAY);
final JMenu[] menu = {new JMenu("File"),// "File"菜单
new JMenu("Edit"),// "Edit"菜单
new JMenu("Font"), //"Font"菜单
new JMenu("Help")// "Help"菜单
}; final JMenuItem[][] menuItem = {
{new JMenuItem("New"), new JMenuItem("Open"),
new JMenuItem("Save"), new JMenuItem("Exit")},
{new JMenuItem("Cut"), new JMenuItem("Copy"),
new JMenuItem("Paste")},
{},
{new JMenuItem("Help"), new JMenuItem("About")}};
for (int i = 0; i < menu.length; i++) {
for (int j = 0; j < menuItem[i].length; j++)
{
menuItem[i][j].setBackground(Color.LIGHT_GRAY);
menu[i].add(menuItem[i][j]);
menuItem[i][j].addActionListener(this);
}
menuBar.add(menu[i]);
}
menu[0].add(new JSeparator(), 3); // 特定地方补分隔符
// 工具栏初始化
JToolBar toolBar = new JToolBar();
String[] toolButtonText =
{"New","Open","Exit"};
JButton[] toolButton = new JButton[toolButtonText.length];
for(int i=0;i<toolButtonText.length;i++)
{
toolButton[i] = new JButton(toolButtonText[i]);
}
for(int i=0;i<toolButton.length;i++)
{
toolButton[i].setActionCommand(toolButtonText[i]);
toolButton[i].addActionListener(this);
toolBar.add(toolButton[i]);
}
// 文本框 textEdit = new JEditorPane();
textEdit.setBackground(Color.DARK_GRAY);
textEdit.setForeground(Color.LIGHT_GRAY);
textEdit.getDocument().addDocumentListener(this);
// 为文本域添加滑动块
JScrollPane scrollPane = new JScrollPane(textEdit); // 初始化状态栏
JToolBar statusBar = new JToolBar();
statusBar.setFloatable(false);
statusBar.setBackground(Color.LIGHT_GRAY);
statusLabel = new JLabel(" ");
statusBar.add(statusLabel); // 初始化面板
panel = new JPanel();
panel.setLayout(new BorderLayout());
//panel.add(toolBar,BorderLayout.PAGE_START);
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(statusBar, BorderLayout.PAGE_END); this.add(panel);
this.setJMenuBar(menuBar);
this.setTitle("NoteBook");
this.setSize(640, 480);
this.setVisible(true);
}
// 参数初始化
public void InitPara() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
clip = toolkit.getSystemClipboard();
TextChangeNoSave = false;
DocIsNew = true;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
switch (e.getActionCommand()) {
// File菜单的事件响应
case "New" :
newFile();
break;
case "Open" :
openFile();
break;
case "Save" :
saveFile();
break;
case "Exit" :
exit();
break;
// Edit菜单事件响应
case "Cut" :
cutText();
break;
case "Copy" :
copyText();
break;
case "Paste" :
pasteText();
break; // Help菜单事件响应
case "Help" :
help();
break;
case "About" :
about();
break;
default :
break;
}
} // ////菜单功能函数
public void newFile() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
}
}
textEdit.setText("");
statusLabel.setText("Created a new file");
DocIsNew = true;
TextChangeNoSave = true;
filePath = null;
fileName = null;
}
public void openFile() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
} }
FileDialog openFileDlg = new FileDialog(this, "打开文件", FileDialog.LOAD);
openFileDlg.setVisible(true);
filePath = openFileDlg.getDirectory();
fileName = openFileDlg.getFile();
ReadFile();
TextChangeNoSave = false;
DocIsNew = false; }
public void saveFile() {
if (DocIsNew) {
FileDialog saveFileDlg = new FileDialog(this, "保存文件",
FileDialog.SAVE);
saveFileDlg.setVisible(true);
filePath = saveFileDlg.getDirectory();
fileName = saveFileDlg.getFile();
}
WriteFile();
}
public void exit() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
}
}
System.exit(0);
}
public void cutText() {
textEdit.cut();
}
public void copyText() {
textEdit.copy();
}
public void pasteText() {
Transferable contents = clip.getContents(this);
if (contents != null
&& contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
String str = (String) contents
.getTransferData(DataFlavor.stringFlavor);
int pos = textEdit.getSelectionStart();
textEdit.cut();
textEdit.insert(str, pos);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void help() {
//File dir = new File("..");
//filePath = dir.getAbsolutePath();
fileName = "readme.txt";
ReadFile();
}
public void about() {
String info = "作者 :nudt_tony \n" + "日期 :2013 06 28\n"
+ "邮箱 :[email protected]";
JOptionPane.showMessageDialog(this, info);
}
// /底层文件读写函数
public void WriteFile() {
if (fileName != null) {
try {
File file1 = new File(filePath, fileName);
FileWriter fw = new FileWriter(file1);
BufferedWriter out = new BufferedWriter(fw);
out.write(textEdit.getText());
out.close();
fw.close();
statusLabel.setText("文件保存成功!");
} catch (IOException e) {
statusLabel.setText("文件保存出错!");
}
}
} public void ReadFile() {
if (fileName != null) {
try {
File file1 = new File(filePath, fileName);
FileReader fr = new FileReader(file1);
BufferedReader in = new BufferedReader(fr);
StringBuilder text = new StringBuilder();
String str="";
while ((str = in.readLine()) != null)
{
text.append(str+ "\r\n");
}
textEdit.setText(text.toString());
in.close();
fr.close();
statusLabel.setText(filePath + fileName); } catch (IOException e) {
statusLabel.setText("打开文件出错!");
}
}
} @Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
// statusLabel.setText("Text Changed!!");
TextChangeNoSave = true;
statusLabel.setText("Text insertUpdate!");
}
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
TextChangeNoSave = true;
statusLabel.setText("Text removeUpdate!!");
}
@Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
TextChangeNoSave = true;
statusLabel.setText("Text changedUpdate!!");
}
}
这个是测试类
package study.com.notebook;public class TestClass { public static void main(String[] args) {
MainForm mainform = new MainForm();
}}
文本编辑Java
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.JButton;
import javax.swing.JEditorPane;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.StyleConstants;class MainForm extends JFrame implements ActionListener, DocumentListener {
/**
*
*/
private static final long serialVersionUID = 1L;
// 界面元素变量
JMenuBar menuBar; // 菜单
JPanel panel;
JEditorPane textEdit;
JLabel statusLabel; // 控制变量
boolean TextChangeNoSave; // 当前文档的改变是否已经保存
boolean DocIsNew; // 当前文档是否为新建 // 当前文件名次、路径
String filePath;
String fileName; // 系统粘贴板
Clipboard clip; public MainForm() {
// 界面初始化
InitGUI();
InitPara();
} // 界面初始化
public void InitGUI() {
// 菜单栏初始化
menuBar = new JMenuBar();
menuBar.setBackground(Color.LIGHT_GRAY);
final JMenu[] menu = {new JMenu("File"),// "File"菜单
new JMenu("Edit"),// "Edit"菜单
new JMenu("Font"), //"Font"菜单
new JMenu("Help")// "Help"菜单
}; final JMenuItem[][] menuItem = {
{new JMenuItem("New"), new JMenuItem("Open"),
new JMenuItem("Save"), new JMenuItem("Exit")},
{new JMenuItem("Cut"), new JMenuItem("Copy"),
new JMenuItem("Paste")},
{},
{new JMenuItem("Help"), new JMenuItem("About")}};
for (int i = 0; i < menu.length; i++) {
for (int j = 0; j < menuItem[i].length; j++)
{
menuItem[i][j].setBackground(Color.LIGHT_GRAY);
menu[i].add(menuItem[i][j]);
menuItem[i][j].addActionListener(this);
}
menuBar.add(menu[i]);
}
menu[0].add(new JSeparator(), 3); // 特定地方补分隔符
// 工具栏初始化
JToolBar toolBar = new JToolBar();
String[] toolButtonText =
{"New","Open","Exit"};
JButton[] toolButton = new JButton[toolButtonText.length];
for(int i=0;i<toolButtonText.length;i++)
{
toolButton[i] = new JButton(toolButtonText[i]);
}
for(int i=0;i<toolButton.length;i++)
{
toolButton[i].setActionCommand(toolButtonText[i]);
toolButton[i].addActionListener(this);
toolBar.add(toolButton[i]);
}
// 文本框 textEdit = new JEditorPane();
textEdit.setBackground(Color.DARK_GRAY);
textEdit.setForeground(Color.LIGHT_GRAY);
textEdit.getDocument().addDocumentListener(this);
// 为文本域添加滑动块
JScrollPane scrollPane = new JScrollPane(textEdit); // 初始化状态栏
JToolBar statusBar = new JToolBar();
statusBar.setFloatable(false);
statusBar.setBackground(Color.LIGHT_GRAY);
statusLabel = new JLabel(" ");
statusBar.add(statusLabel); // 初始化面板
panel = new JPanel();
panel.setLayout(new BorderLayout());
//panel.add(toolBar,BorderLayout.PAGE_START);
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(statusBar, BorderLayout.PAGE_END); this.add(panel);
this.setJMenuBar(menuBar);
this.setTitle("NoteBook");
this.setSize(640, 480);
this.setVisible(true);
}
// 参数初始化
public void InitPara() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
clip = toolkit.getSystemClipboard();
TextChangeNoSave = false;
DocIsNew = true;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
switch (e.getActionCommand()) {
// File菜单的事件响应
case "New" :
newFile();
break;
case "Open" :
openFile();
break;
case "Save" :
saveFile();
break;
case "Exit" :
exit();
break;
// Edit菜单事件响应
case "Cut" :
cutText();
break;
case "Copy" :
copyText();
break;
case "Paste" :
pasteText();
break; // Help菜单事件响应
case "Help" :
help();
break;
case "About" :
about();
break;
default :
break;
}
} // ////菜单功能函数
public void newFile() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
}
}
textEdit.setText("");
statusLabel.setText("Created a new file");
DocIsNew = true;
TextChangeNoSave = true;
filePath = null;
fileName = null;
}
public void openFile() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
} }
FileDialog openFileDlg = new FileDialog(this, "打开文件", FileDialog.LOAD);
openFileDlg.setVisible(true);
filePath = openFileDlg.getDirectory();
fileName = openFileDlg.getFile();
ReadFile();
TextChangeNoSave = false;
DocIsNew = false; }
public void saveFile() {
if (DocIsNew) {
FileDialog saveFileDlg = new FileDialog(this, "保存文件",
FileDialog.SAVE);
saveFileDlg.setVisible(true);
filePath = saveFileDlg.getDirectory();
fileName = saveFileDlg.getFile();
}
WriteFile();
}
public void exit() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
}
}
System.exit(0);
}
public void cutText() {
textEdit.cut();
}
public void copyText() {
textEdit.copy();
}
public void pasteText() {
Transferable contents = clip.getContents(this);
if (contents != null
&& contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
String str = (String) contents
.getTransferData(DataFlavor.stringFlavor);
int pos = textEdit.getSelectionStart();
textEdit.cut();
textEdit.insert(str, pos);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void help() {
//File dir = new File("..");
//filePath = dir.getAbsolutePath();
fileName = "readme.txt";
ReadFile();
}
public void about() {
String info = "作者 :nudt_tony \n" + "日期 :2013 06 28\n"
+ "邮箱 :[email protected]";
JOptionPane.showMessageDialog(this, info);
}
// /底层文件读写函数
public void WriteFile() {
if (fileName != null) {
try {
File file1 = new File(filePath, fileName);
FileWriter fw = new FileWriter(file1);
BufferedWriter out = new BufferedWriter(fw);
out.write(textEdit.getText());
out.close();
fw.close();
statusLabel.setText("文件保存成功!");
} catch (IOException e) {
statusLabel.setText("文件保存出错!");
}
}
} public void ReadFile() {
if (fileName != null) {
try {
File file1 = new File(filePath, fileName);
FileReader fr = new FileReader(file1);
BufferedReader in = new BufferedReader(fr);
StringBuilder text = new StringBuilder();
String str="";
while ((str = in.readLine()) != null)
{
text.append(str+ "\r\n");
}
textEdit.setText(text.toString());
in.close();
fr.close();
statusLabel.setText(filePath + fileName); } catch (IOException e) {
statusLabel.setText("打开文件出错!");
}
}
} @Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
// statusLabel.setText("Text Changed!!");
TextChangeNoSave = true;
statusLabel.setText("Text insertUpdate!");
}
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
TextChangeNoSave = true;
statusLabel.setText("Text removeUpdate!!");
}
@Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
TextChangeNoSave = true;
statusLabel.setText("Text changedUpdate!!");
}
}
这个是测试类
package study.com.notebook;public class TestClass { public static void main(String[] args) {
MainForm mainform = new MainForm();
}}
文本编辑Java
解决方案 »
- 关于java不用odbc设置数据源连接access的编程问题
- float和Float的区别,floatValue()的作用?
- 2个java基础问题
- 1.6遍历语句怎么不好用
- 80分散分!!解决了就给分,其实是小问题
- 操作oracle结果集的简单问题(结果集指针移动到第一条记录)
- BES VisiBroker Edition 6.5 安装完成后,VisiBroker Console 打开时报 Error type: java.lang.NoClassDefFoundError
- 高手请进:为什么 -1/2 值为0, 而 -1>>1 的值为-1呢?
- 谁有JBuilder 8 企业试用版的 License ??
- 我刚学jbuilder,很菜,各位前辈,请帮帮我的忙!!!!!!!!!!!!!!!!!!!!!!!!!!1
- 特定的字符串的查找,比如在一段字符串中查找for后面的判断语句while,do while, else if,if 后面的判定语句
- 如何利用Java实现和Windows完全相同的文件打开/保存对话框
以前用C#的,类似程序写得比较多,这次算JAVA纯白动手吧,不过自己有点C c++ c#的编程基础,所以直接JAVA没感觉很难,有百度,哈哈
NoteBook是一个文本编辑器,实现文本文件的简单编辑和阅读功能。其实现文件功能为:新建文本文件,查看文本文件,修改文本并保存等基本功能。其实现编辑功能为:剪切、复制和粘贴。一、学习实现步骤
1、确定技术路线
因为这个文本编辑器,有一个菜单栏,一个文本框,一个状态栏,因此涉及GUI编程,于是百度“JAVA GUI”,出来一堆结果,大体是使用awt和swing库,然后通过layout布局管理界面,还有使用插件可视编程。
决定1:使用swing库,通过代码实现界面,整个编辑器写一个窗口类(继承自JFrame,用于主main函数调用显示。(C#也是如此干的)
2、确定程序逻辑,业务流程
程序运行后,主界面显示出来后,这时可以有很多操作,如果当前文本文件已改变,那么再新建或是打开其他文件,需要确认是否保存当前已改变的文件,这是WINDOWS 文本等程序都有的功能。
决定2: 真实底层文件读写两个函数,业务逻辑在功能函数里面明确。功能函数明确业务逻辑后,根据需要调用文件读写函数。
3、确定swing可以使用的控件变量
依据上面,我必须要菜单栏,工具栏(已实现,但未显示而已),文本输入框,状态栏。
依次百度:JAVA SWING 菜单栏
JAVA SWING工具栏栏
JAVA SWING 文本输入
JAVA SWING 状态栏
出来一堆,研读之下,有了JMenuBar , JPanel,JEditArea(开始使用,后改为JEditorPane) ,JLabel,JMenu等等相关控件在网页里面的代码出现,看名字就知道他们是个什么东东。界面有办法解决了,如何确定按钮事件和处理函数挂钩?同样百度,知道了ActionListener。参看代码,照猫画虎知道怎么用了,具体里面不懂,先不管,写起来再说。
决定3: 程序界面初始化仿照C#单写一个函数(InitGui()),于是InitGui函数出来了,根据个人爱好对控件背景色等调了调。
4、确定功能函数
依据上一步,知道菜单按钮事件需添加监控,于是
addActionListener
自动有提示添加
actionPerformed()
里面采用开关实现各个按钮。
又如何将工具栏按钮与对应功能函数挂钩?
利用setActionCommand
,设置好按钮对应的命令文本即可。至此,基本程序框架就全了,剪贴板操作,文件读写,文件对话框,信息显示对话框等什么的都交给百度吧,基本都有。
就这样,一下午过去了
谢谢,你还真仔细,确实使用了粘贴功能。
我开始是用的这个JTextArea类,后来换了,没有仔细测试。
你换回来看看,注意界面初始化里面也换回来,就这两个地方。
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.JButton;
import javax.swing.JEditorPane;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;class MainForm extends JFrame implements ActionListener, DocumentListener {
private static final long serialVersionUID = 1L;
// 界面元素变量
JMenuBar menuBar; // 菜单
JPanel panel;
JTextArea textEdit;
JLabel statusLabel; // 控制变量
boolean TextChangeNoSave;
// 当前文档的改变是否已经保存
boolean DocIsNew;
// 当前文档是否为新建 // 当前文件名次、路径
String filePath;
String fileName; // 系统粘贴板
Clipboard clip; public MainForm() {
// 界面初始化
InitGUI();
InitPara();
} // 界面初始化
public void InitGUI() {
// 菜单栏初始化
menuBar = new JMenuBar();
menuBar.setBackground(Color.LIGHT_GRAY);
final JMenu[] menu = {new JMenu("File"),// "File"菜单
new JMenu("Edit"),// "Edit"菜单
new JMenu("Font"), //"Font"菜单
new JMenu("Help")// "Help"菜单
}; final JMenuItem[][] menuItem = {
{new JMenuItem("New"), new JMenuItem("Open"),
new JMenuItem("Save"), new JMenuItem("Exit")},
{new JMenuItem("Cut"), new JMenuItem("Copy"),
new JMenuItem("Paste")},
{},
{new JMenuItem("Help"), new JMenuItem("About")}};
for (int i = 0; i < menu.length; i++) {
for (int j = 0; j < menuItem[i].length; j++)
{
menuItem[i][j].setBackground(Color.LIGHT_GRAY);
menu[i].add(menuItem[i][j]);
menuItem[i][j].addActionListener(this);
}
menuBar.add(menu[i]);
}
menu[0].add(new JSeparator(), 3); // 特定地方补分隔符
// 工具栏初始化
JToolBar toolBar = new JToolBar();
String[] toolButtonText =
{"New","Open","Exit"};
JButton[] toolButton = new JButton[toolButtonText.length];
for(int i=0;i<toolButtonText.length;i++)
{
toolButton[i] = new JButton(toolButtonText[i]);
}
for(int i=0;i<toolButton.length;i++)
{
toolButton[i].setActionCommand(toolButtonText[i]);
toolButton[i].addActionListener(this);
toolBar.add(toolButton[i]);
}
// 文本框 textEdit = new JTextArea();
textEdit.setBackground(Color.DARK_GRAY);
textEdit.setForeground(Color.LIGHT_GRAY);
textEdit.getDocument().addDocumentListener(this);
// 为文本域添加滑动块
JScrollPane scrollPane = new JScrollPane(textEdit); // 初始化状态栏
JToolBar statusBar = new JToolBar();
statusBar.setFloatable(false);
statusBar.setBackground(Color.LIGHT_GRAY);
statusLabel = new JLabel(" ");
statusBar.add(statusLabel); // 初始化面板
panel = new JPanel();
panel.setLayout(new BorderLayout());
//panel.add(toolBar,BorderLayout.PAGE_START);
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(statusBar, BorderLayout.PAGE_END); this.add(panel);
this.setJMenuBar(menuBar);
this.setTitle("NoteBook");
this.setSize(640, 480);
this.setVisible(true);
}
// 参数初始化
public void InitPara() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
clip = toolkit.getSystemClipboard();
TextChangeNoSave = false;
DocIsNew = true;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
switch (e.getActionCommand()) {
// File菜单的事件响应
case "New" :
newFile();
break;
case "Open" :
openFile();
break;
case "Save" :
saveFile();
break;
case "Exit" :
exit();
break;
// Edit菜单事件响应
case "Cut" :
cutText();
break;
case "Copy" :
copyText();
break;
case "Paste" :
pasteText();
break; // Help菜单事件响应
case "Help" :
help();
break;
case "About" :
about();
break;
default :
break;
}
} // ////菜单功能函数
public void newFile() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
}
}
textEdit.setText("");
statusLabel.setText("Created a new file");
DocIsNew = true;
TextChangeNoSave = true;
filePath = null;
fileName = null;
}
public void openFile() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
} }
FileDialog openFileDlg = new FileDialog(this, "打开文件", FileDialog.LOAD);
openFileDlg.setVisible(true);
filePath = openFileDlg.getDirectory();
fileName = openFileDlg.getFile();
ReadFile();
TextChangeNoSave = false;
DocIsNew = false; }
public void saveFile() {
if (DocIsNew) {
FileDialog saveFileDlg = new FileDialog(this, "保存文件",
FileDialog.SAVE);
saveFileDlg.setVisible(true);
filePath = saveFileDlg.getDirectory();
fileName = saveFileDlg.getFile();
}
WriteFile();
}
public void exit() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
}
}
System.exit(0);
}
public void cutText() {
textEdit.cut();
}
public void copyText() {
textEdit.copy();
}
public void pasteText() {
Transferable contents = clip.getContents(this);
if (contents != null
&& contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
String str = (String) contents
.getTransferData(DataFlavor.stringFlavor);
int pos = textEdit.getSelectionStart();
textEdit.cut();
textEdit.insert(str, pos);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void help() {
//File dir = new File("..");
//filePath = dir.getAbsolutePath();
fileName = "readme.txt";
ReadFile();
}
public void about() {
String info = "作者 :nudt_tony \n" + "日期 :2013 06 28\n"
+ "邮箱 :[email protected]";
JOptionPane.showMessageDialog(this, info);
}
// /底层文件读写函数
public void WriteFile() {
if (fileName != null) {
try {
File file1 = new File(filePath, fileName);
FileWriter fw = new FileWriter(file1);
BufferedWriter out = new BufferedWriter(fw);
out.write(textEdit.getText());
out.close();
fw.close();
statusLabel.setText("文件保存成功!");
} catch (IOException e) {
statusLabel.setText("文件保存出错!");
}
}
} public void ReadFile() {
if (fileName != null) {
try {
File file1 = new File(filePath, fileName);
FileReader fr = new FileReader(file1);
BufferedReader in = new BufferedReader(fr);
StringBuilder text = new StringBuilder();
String str="";
while ((str = in.readLine()) != null)
{
text.append(str+ "\r\n");
}
textEdit.setText(text.toString());
in.close();
fr.close();
statusLabel.setText(filePath + fileName); } catch (IOException e) {
statusLabel.setText("打开文件出错!");
}
}
} @Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
// statusLabel.setText("Text Changed!!");
TextChangeNoSave = true;
statusLabel.setText("Text insertUpdate!");
}
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
TextChangeNoSave = true;
statusLabel.setText("Text removeUpdate!!");
}
@Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
TextChangeNoSave = true;
statusLabel.setText("Text changedUpdate!!");
}
}
谢谢
有疑惑,望解答下:
你说的逻辑和界面分离?我界面一个函数,包含界面构造,和控件事件响应设定,功能逻辑在各功能函数里面。还如何分离,望指点下下。
新建一个类,只处理逻辑,然后由构造函数传入该类实例。这里文件存取逻辑可以拆分,作为一个通用类,这样其他的程序或者本程序的其他功能也可以使用。
避免在构造函数里调用任何可以被重写的方法,会产生意想不到的效果。这个写多了自然会碰到的
“这里文件存取逻辑可以拆分”非常感谢,我写的时候,也隐隐感觉这块存在一个逻辑关系,而且我的文件存取这块,确实有一个判断代码块是重复的,当时我也想单独写入一个函数,看起来更清晰。但是如何将器逻辑提取写入一个类,而且还能让其他地方可以使用?摸不这头脑啊!!!
难到这个逻辑类里面,只包含一些逻辑变量(boolean)?主界面传递这些逻辑变量到逻辑类?然后逻辑类返回判断结果?
如果主界面函数根据返回结果判断操作?那么还是要if else 啊?能否提供一个简单的实例,或者给个能用的关键字,我搜索?
新手望指点啊!!
谢谢
有疑惑,望解答下:
你说的逻辑和界面分离?我界面一个函数,包含界面构造,和控件事件响应设定,功能逻辑在各功能函数里面。还如何分离,望指点下下。
新建一个类,只处理逻辑,然后由构造函数传入该类实例。这里文件存取逻辑可以拆分,作为一个通用类,这样其他的程序或者本程序的其他功能也可以使用。
避免在构造函数里调用任何可以被重写的方法,会产生意想不到的效果。这个写多了自然会碰到的
“这里文件存取逻辑可以拆分”非常感谢,我写的时候,也隐隐感觉这块存在一个逻辑关系,而且我的文件存取这块,确实有一个判断代码块是重复的,当时我也想单独写入一个函数,看起来更清晰。但是如何将器逻辑提取写入一个类,而且还能让其他地方可以使用?摸不这头脑啊!!!
想了想,难到这个逻辑类里面,纯文档处理?就是文本的读取,写入等等都放入一个类?类似这个DefaultEditorKit类的功能?
类似上面
首先你需要三个文件,分别是两个接口和一个类:
public interface TextFileReadEventListener {
void onFileRead(final String text, final String path);
}
public interface TextFileWriteEventListener {
void onFileWritten();
}
public class TextFileIOHelper {
public static void readFile(final String path, final TextFileReadEventListener listener) throws IOException {
if (path != null) {
File file1 = new File(path);
FileReader fr = new FileReader(file1);
BufferedReader in = new BufferedReader(fr);
StringBuilder text = new StringBuilder();
String str = "";
while ((str = in.readLine()) != null) {
text.append(str + "\r\n");
}
in.close();
fr.close(); listener.onFileRead(text.toString(), path);
}
} public static void writeFile(final String path, final String text, final TextFileWriteEventListener listener)
throws IOException {
if (path != null) {
File file1 = new File(path);
FileWriter fw = new FileWriter(file1);
BufferedWriter out = new BufferedWriter(fw);
out.write(text);
out.close();
fw.close();
listener.onFileWritten();
}
}
}
然后稍微改一下你的save/open函数:
public void openFile() {
if (TextChangeNoSave) {
int n = JOptionPane.showConfirmDialog(this, "文件已更改,是否保存?", "提示!", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
saveFile();
} }
FileDialog openFileDlg = new FileDialog(this, "打开文件", FileDialog.LOAD);
openFileDlg.setVisible(true);
filePath = openFileDlg.getDirectory();
fileName = openFileDlg.getFile();
ReadFile();
TextChangeNoSave = false;
DocIsNew = false; if (fileName != null) {
try {
TextFileIOHelper.readFile(filePath + System.lineSeparator() + fileName, new TextFileReadEventListener() {
@Override
public void onFileRead(final String text, final String path) {
textEdit.setText(text);
statusLabel.setText(path);
}
});
}
catch (IOException e) {
statusLabel.setText("打开文件出错!");
}
}
}public void saveFile() {
if (!DocIsNew)
return; FileDialog saveFileDlg = new FileDialog(this, "保存文件", FileDialog.SAVE);
saveFileDlg.setVisible(true);
filePath = saveFileDlg.getDirectory();
fileName = saveFileDlg.getFile(); if (fileName != null) {
try {
TextFileIOHelper.writeFile(filePath + System.lineSeparator() + fileName, textEdit.getText(),
new TextFileWriteEventListener() {
@Override
public void onFileWritten() {
statusLabel.setText("文件保存成功!");
}
});
}
catch (IOException e) {
statusLabel.setText("文件保存出错!");
}
}
}这样如果你以后有程序想用read/write file函数,就可以直接调用。当然还有很多很多其他的方法能做到,这里只是举一个比较“飘逸”的例子