您的位置:首页 > 编程语言 > Java开发

【无浪】花了两周时间纯手打打出来的Java记事本

2014-11-23 08:55 288 查看
最近的大作业是记事本,两周的大块时间和碎片时间都花在这上面了,数据结构已经落下了,要恶补了。

注意这个记事本在没有联网的时候会在关于记事本类中的一个JLabel标签里停下,该标签使用了HTML连向一张图片,所以不联网的时候把这个JLabel删掉即可打开,或者联网就能正常打开。

PS:由于当时是初学Java,看到中文能作为变量名很新鲜,且这样子可读性较好。但是建议Java不要用中文名。

手推代码帮了很多忙。

难度以★来表示

1.Windows记事本已有功能:

【新建】(★★★)

【打开】(★★★)

【保存】(★★★★)

【另存为】(★★★)

【页面设置】(★★)

【打印】(★★★★★)

【退出】(★★)

【撤销】(★★)

【剪切】(★)

【复制】(★)

【粘贴】(★)

【删除】(★)

【查找】(★★★★★)

【查找下一个】(★)

【替换】(★)

【转到】(★)

【全选】()

【时间日期】()

【自动换行】()

【字体】(★)

【状态栏】()

【帮助文档】(★★)

【关于记事本】(★)

2.自己扩展的功能

【加密解密】(★★★★)

【即时存档】(★★)

【即读读档】(★★)

【清空文本】()

【字体颜色】()

【背景颜色】()

【显示行号】()

[文本区域拖拽字符串移动其位置] (★★★)

[拖动txt文件到文本区域打开文件] (★★)

[文本框左侧显示行数](★★★★)



import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;
import java.util.List;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

//文件->新建N CTRL+N
class NewC implements ActionListener {
private JTextArea editText;
private boolean choose;
public JFrame frame;
public static String path1;//在打开的事件中path1="";
public String str;
NewC() {
this.editText = JLinePrint.editText;
path1="";
NewMenu();
}//新建
public void NewMenu(){
//建立询问框,设置大小位置,设为自己布局
frame=new JFrame("记事本");
frame.setBounds(424, 269, 355, 181);
frame.setLayout(null);
//建立两个标签
JLabel label1=new JLabel("文件的内容已经改变");
label1.setFont(new Font("新宋体",Font.PLAIN,14));
JLabel label2=new JLabel("想保存文件吗?:)");
label2.setFont(new Font("新宋体",Font.PLAIN,14));
label1.setBounds(113,23,180, 23);
label2.setBounds(113,46,180,23);
frame.add(label1);
frame.add(label2);
//建立"是"按钮
JButton button_Yes=new JButton("是(Y)");
button_Yes.setMnemonic(KeyEvent.VK_Y);//按ALT+Y选择
//给"是"按钮加上事件监听
button_Yes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e1){
SaveF.path="";//保存类的路径清空
SaveF.FirstSave=false;//保存类恢复未保存状态
//与另存为相同
choose=false;//条件未满足,不保存
//弹框设定路径
FileDialog filedialog=new FileDialog(frame,"另存为",FileDialog.SAVE);
filedialog.setVisible(true);
path1=filedialog.getDirectory()+filedialog.getFile()+".txt";
//如果为选择路径(文件名为null或nullnull),则直接返回
if(path1.equals("nullnull.txt")||path1.equals(filedialog.getDirectory()+"null.txt"))
{
return;
}//if

final File file=new File(path1);
choose=true;//满足条件,设为能保存状态

if( file.exists()){//如果文件重名
choose=false;            //有条件不满足,重设为不能保存状态
final JFrame f=new JFrame("另存为");
f.setBounds(435,276,path1.length()*7+200,125);
f.setVisible(true);
f.setLayout(null);
JLabel label=new JLabel(path1+"已存在。"+"要替换它吗?");
label.setBounds(20,10,path1.length()*7+130,30);
f.add(label);

JButton button_Yes=new JButton("是(Y)");
button_Yes.setMnemonic(KeyEvent.VK_Y);//按ALT+Y选择
button_Yes.setBounds(43,58,100,30);
button_Yes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
//选择是以后直接保存
//若有文件重名时候的文件输出流,输出后直接退出新建窗口
FileWriter out;
out = new FileWriter(file);
BufferedWriter out_ = new BufferedWriter(out);
String temp[]=str.split("\n");
if (file.canRead()||file.getName()!=null) {
int i=-1;
for(;++i<temp.length-1;){
out_.write(temp[i]);
out_.newLine();
}out_.write(temp[i]);
out_.close();
}//if
editText.setText(null);//把文本框清空
}//try
catch (IOException e3) {
}//catch
f.dispose();

}//actionperformed
});//ActionListener
f.add(button_Yes);

JButton button_No=new JButton("否(N)");
button_No.setMnemonic(KeyEvent.VK_N);//按ALT+N选择
button_No.setBounds(143+path1.length()*4,58,100,30);
button_No.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
f.dispose();
editText.setText(str);
}
});
f.add(button_No);
}//if
//文件不重名时候的文件输出流
if(choose)//如果前面的条件都满足则执行保存命令
{
//文件输出流
try {
FileWriter out;
out = new FileWriter(file);
BufferedWriter out_ = new BufferedWriter(out);
String temp[]=str.split("\n");
if (file.canRead()||file.getName()!=null) {
int i=-1;
for(;++i<temp.length-1;){
out_.write(temp[i]);
out_.newLine();
}out_.write(temp[i]);
out_.close();
}//if
editText.setText(null);
}//try
catch (IOException e3) {
}//catch
}//if
frame.dispose();
}//actionPerformed
});
JButton button_No=new JButton("否(N)");
button_No.setMnemonic(KeyEvent.VK_N);//按ALT+N选择
button_No.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//若选择否则保存条件不满足
choose=false;
JLinePrint.editText.setText(null);
SaveF.path="";//保存恢复
frame.dispose();
}
});
button_Yes.setBounds(81,93,100,30);
button_No.setBounds(211,93,100,30);
frame.add(button_Yes);
frame.add(button_No);
frame.setResizable(false);
}
public void actionPerformed(ActionEvent e) {
//若文件内容有改变,询问用户是否存档
if(Textfieldincident.change){
str=editText.getText();
frame.setVisible(true);
}//if
}//actionPerformed
}//新建

// 文件->打开O CTRL+O
class OpenF implements ActionListener {
private FileDialog filedialog;
private JLinePrint lineprint;
OpenF(JFrame frame,JLinePrint lineprint) {
this.lineprint=lineprint;
filedialog = new FileDialog(frame, "打开", FileDialog.LOAD);
}//打开
public void actionPerformed(ActionEvent e) {
Open();
}//actionPerformed
public void Open(){
String regex="[.txt]";//正则表达式
filedialog.setVisible(true);
if(filedialog.getDirectory()==null)return;//按取消的时候
String Filepath=filedialog.getDirectory();  //获取文件路径,最后面带"\"
String FileName=filedialog.getFile();      //获取文件名字(带.txt)

String path=Filepath + FileName;           //文件路径+文件名字
FileName=FileName.replaceAll(regex, "");   //获取文件名字(不带.txt)
File file = new File(path);
try {
FileReader in = new FileReader(file);
BufferedReader in_ = new BufferedReader(in);
String s = in_.readLine();
String temp = s;
s=in_.readLine();
if (file.canRead()) {
while (s != null) {
temp +=("\r\n"+s);                //存在一个String里面,到时候一次性赋给JTextArea
s = in_.readLine();                  //一行一行读取
}//while
JLinePrint.editText.setText(temp);
in_.close();
//读入即时存档文件
for(int i=0;++i<11;){
File file1=new File(Filepath+FileName+String.valueOf(i)+".txt");//文件路径+文件名(不带.txt)+存档编号+.txt
if(file1.exists()){
in = new FileReader(file1);
in_ = new BufferedReader(in);
s = in_.readLine();//第一行读取 时间
Notepad.Save_subMenu[i-1].setText(s);//给即时存档子菜单改变时间;保存文件名在后面加1-10,数组下标由0-9
Notepad.Load_subMenu[i-1].setText(s);//给即时读档子菜单改变时间
s=in_.readLine();//第二行开始读取正文
temp = "";
if (file1.canRead()) {
while (s != null) {
temp += (s + "\r\n");
s = in_.readLine();
}//while
Notepad.Save[i-1].s=temp;
Notepad.Load[i-1].s=Notepad.Save[i-1];
in_.close();
}//if
}//if
else{//如果没有该编号的存档
Notepad.Save_subMenu[i-1].setText("--------/--------     ");//给即时存档子菜单改变时间;
Notepad.Load_subMenu[i-1].setText("--------/--------     ");//给即时读档子菜单改变时间;
Notepad.Save[i-1].s="";
Notepad.Load[i-1].s=Notepad.Save[i-1];
}//else
}//for
lineprint.repaint_1();
final JFrame frame = new JFrame("读入成功!");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(null);
frame.setBounds(300, 400, 250, 125);
frame.setVisible(true);
JButton button = new JButton("确定");
button.setBounds(75, 50, 100, 30);
frame.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}//actionPerformed
});//addActionListener

// (String) File.getParent()返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。
//(File) File.getParentFile()返回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录,则返回 null。
SaveF.fileName=FileName+".txt";//获取文本名字
SaveF.filepath=path.replace("\\"+FileName+".txt", "");//获取路径名字,这个路径没有XX.txt
SaveF.path=path;//打开的时候保存路径已设好   这个路径有XX.txt
SaveF.FirstSave=true;//打开的时候算作有第一次保存,CTRL+S无需弹框保存
NewC.path1="";//新建恢复
}//if
}//try
catch (IOException e1) {
}//catch
}//Open
}//打开

//文件->保存||另存为
class SaveF implements ActionListener{//囊括了保存和另存为
private JTextArea editText;
private FileDialog filedialog;
public static String path;//path用于"保存"菜单项;在即时存档中检测有无保存;在新建中在选择过后path恢复为"";在打开的时候直接获取path,同时控制在保存一次后不再弹出保存对话框
private String path1;//;path1用于"另存为"菜单项
public static boolean FirstSave;//用于在"保存"菜单项中判断是否为第一次保存;在新建中保存后FirstSave赋值为false;在打开类中打开文件后FirstSave赋值为true
private boolean choose;//文件重名时候的选择为true or false
public static String filepath;//filepath文件路径名,用于即时存档; 在打开中获取文件路径
public static String fileName;//fileName文件名,用于即时存档;在打开中获取文件名
SaveF(JFrame frame){
this.editText=JLinePrint.editText;
filedialog=new FileDialog(frame,"保存",FileDialog.SAVE);
path="";
FirstSave=false;
}//保存
public void actionPerformed(ActionEvent e){
choose=false;
if(((JMenuItem)e.getSource()).getActionCommand().equals("保存(S)")){
Save();
}//if("保存(S)")
else if(((JMenuItem)e.getSource()).getActionCommand().equals("另存为(A)...")){
Resave();
}//另存为(A)...
}//actionPerformed
public void Save(){
if(path.equals("")){//如果文件路径为空则弹框获得文件路径
filedialog.setVisible(true);
filepath=filedialog.getDirectory();
fileName=filedialog.getFile();
path=filepath+fileName+".txt";
}//if
if(path.equals("nullnull.txt")||path.equals(filedialog.getDirectory()+"null.txt"))
{
path="";
return;
}//if
choose=true;
File file=new File(path);
if(!FirstSave && file.exists()){//如果不是第一次保存同时文件重名
final JFrame f=new JFrame("另存为");
f.setBounds(435,276,path.length()*7+200,125);
f.setVisible(true);
f.setLayout(null);
JLabel label=new JLabel(path+"已存在。"+"要替换它吗?");
label.setBounds(20,10,path.length()*7+130,30);
f.add(label);
JButton button_Yes=new JButton("是(Y)");
button_Yes.setMnemonic(KeyEvent.VK_Y);//按ALT+Y选择
button_Yes.setBounds(43,58,100,30);
button_Yes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
choose=true;
FirstSave=true;
f.dispose();
}
});//ActionListener
f.add(button_Yes);

JButton button_No=new JButton("否(N)");
button_No.setMnemonic(KeyEvent.VK_N);//按ALT+N选择
button_No.setBounds(143+path.length()*4,58,100,30);
button_No.addActionListener(new ActionListener(){
//添加事件,在确认是否覆盖的时候选择否,不保存,重置第一次存储,路径重置
public void actionPerformed(ActionEvent e)
{
choose=false;
FirstSave=false;
path="";
f.dispose();

}
});
f.add(button_No);
}//if
if(choose)
{
//文件输出流
try {
FirstSave=true;
FileWriter out;
out = new FileWriter(file);
BufferedWriter out_ = new BufferedWriter(out);
String s=editText.getText();
String temp[]=s.split("\n");
if (file.canRead()||file.getName()!=null) {
int i=-1;
for(;++i<temp.length-1;){
out_.write(temp[i]);
out_.newLine();
}out_.write(temp[i]);
out_.close();
}//if
}//try
catch (IOException e1) {
}//catch
}//if
}//Save

public void Resave(){
//另存为没有保存那么麻烦,保存存储一次后不再弹打开框,直接以原路径保存;另存为需要不断弹出打开框来进行保存。
filedialog.setVisible(true);
path1=filedialog.getDirectory()+filedialog.getFile()+".txt";
if(path1.equals("nullnull.txt")||path1.equals(filedialog.getDirectory()+"null.txt"))
{
return;
}//if
File file=new File(path1);
choose=true;
if(!FirstSave && file.exists()){//如果不是第一次保存同时文件重名
final JFrame f=new JFrame("另存为");
f.setBounds(435,276,path1.length()*7+200,125);
f.setVisible(true);
f.setLayout(null);
JLabel label=new JLabel(path1+"已存在。"+"要替换它吗?");
label.setBounds(20,10,path1.length()*7+130,30);
f.add(label);
JButton button_Yes=new JButton("是(Y)");
button_Yes.setMnemonic(KeyEvent.VK_Y);//按ALT+Y选择
button_Yes.setBounds(43,58,100,30);
button_Yes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
choose=true;
f.dispose();

}
});//ActionListener
f.add(button_Yes);

JButton button_No=new JButton("否(N)");
button_No.setMnemonic(KeyEvent.VK_N);//按ALT+N选择
button_No.setBounds(143+path1.length()*4,58,100,30);
button_No.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
choose=false;
f.dispose();
}
});
f.add(button_No);
}//if
if(choose)
{
//文件输出流
try {
FirstSave=true;
FileWriter out;
out = new FileWriter(file);
BufferedWriter out_ = new BufferedWriter(out);
String s=editText.getText();
String temp[]=s.split("\n");
if (file.canRead()||file.getName()!=null) {
int i=-1;
for(;++i<temp.length-1;){
out_.write(temp[i]);
out_.newLine();
}out_.write(temp[i]);
out_.close();
}//if
}//try
catch (IOException e1) {
}//catch
}//if
}//Resave
}//保存

//文件->页面设置
class PageSetting implements ActionListener{//页面设置1
private JFrame frame;
PageSetting(){
frame=new JFrame("页面设置");
frame.setBounds(419,244,472,323);
frame.setLayout(new GridLayout(5,1));
JPanel Pane=new JPanel();
//设置每一页打印的行数
final JLabel LineEveryPage_set=new JLabel("每一页输出 "+Printout.LineEverypage+" 行");
LineEveryPage_set.setForeground(Color.blue);
LineEveryPage_set.setFont(new Font("华文行楷",Font.BOLD,24));
final JTextField LineEverypage_set1=new JTextField(5);
final JLabel LineEveryPage_status=new JLabel("默认");
LineEverypage_set1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int s=Integer.parseInt(e.getActionCommand());
if(s<=0||s>100){
LineEverypage_set1.setText(null);
LineEveryPage_status.setText("限制在1-100之间");
return;
}
Printout.LineEverypage=s;
LineEveryPage_set.setText("每一页输出 "+Printout.LineEverypage+" 行");
if(Printout.LineEverypage==80){
LineEveryPage_status.setText("默认");
}//if
else{
LineEveryPage_status.setText("已修改");
}//else
LineEverypage_set1.setText(null);
}//actionPerformed
});//addActionListener
Pane.add(LineEveryPage_set);
Pane.add(LineEverypage_set1);
Pane.add(LineEveryPage_status);
Pane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("修改打印时每一页打印的行数"),BorderFactory.createEmptyBorder()));
frame.add(Pane);

//设置x的坐标偏移量
JPanel Pane1=new JPanel();
final JLabel set_x=new JLabel("x坐标的偏移量  x="+Print.start_x);
set_x.setFont(new Font("华文楷体",Font.BOLD,24));
set_x.setForeground(Color.green);
final JTextField set_x1=new JTextField(5);
final JLabel set_x_status=new JLabel("默认");
set_x1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
double s=Double.parseDouble(e.getActionCommand());
if(s<0||s>100){
set_x1.setText(null);
set_x_status.setText("限制在0-100之间");
return;
}
Print.start_x=s;
set_x.setText("x坐标的偏移量  x="+Print.start_x);
if(Print.start_x==50.0){
set_x_status.setText("默认");
}//if
else{
set_x_status.setText("已修改");
}//else
set_x1.setText(null);
}
});
Pane1.add(set_x);
Pane1.add(set_x1);
Pane1.add(set_x_status);
Pane1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("修改打印时起点坐标在x轴的偏移量"),BorderFactory.createEmptyBorder()));
frame.add(Pane1);

//设置y的坐标偏移量
JPanel Pane2=new JPanel();
final JLabel set_y=new JLabel("y坐标的偏移量 y="+Print.start_y);
set_y.setFont(new Font("方正舒体",Font.BOLD,24));
set_y.setForeground(Color.red);
final JTextField set_y1=new JTextField(5);
final JLabel set_y_status=new JLabel("默认");
set_y1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
double s=Double.parseDouble(e.getActionCommand());
if(s<0||s>100){
set_y1.setText(null);
set_y_status.setText("限制在0-100之间");
return;
}
Print.start_y=s;
set_y.setText("y坐标的偏移量 y="+Print.start_y);
if(Print.start_y==20.0){
set_y_status.setText("默认");
}//if
else{
set_y_status.setText("已修改");
}//else
set_y1.setText(null);
}
});

Pane2.add(set_y);
Pane2.add(set_y1);
Pane2.add(set_y_status);
Pane2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("修改打印时起点坐标在y轴的偏移量"),BorderFactory.createEmptyBorder()));
frame.add(Pane2);

//设置行与行之间的间距
JPanel pane4=new JPanel();
final JLabel setinterval=new JLabel("行与行之间的间距为"+Print.interval);
setinterval.setFont(new Font("黑体",Font.BOLD,24));
setinterval.setForeground(Color.PINK);
final JTextField textfield_setinterval=new JTextField(5);
final JLabel setinterval_status=new JLabel("默认");
textfield_setinterval.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int s=Integer.parseInt(e.getActionCommand());
if(s<0||s>100){
textfield_setinterval.setText(null);
setinterval_status.setText("限制在0-100之间");
return;
}
Print.interval=s;
setinterval.setText("行与行之间的间距为"+Print.interval);
if(Print.interval==10){
setinterval_status.setText("默认");
}//if
else{
setinterval_status.setText("已修改");
}//else
textfield_setinterval.setText(null);
}
});
pane4.add(setinterval);
pane4.add(textfield_setinterval);
pane4.add(setinterval_status);
pane4.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("修改打印时行与行的间距"),BorderFactory.createEmptyBorder()));
frame.add(pane4);

//按钮,恢复默认
JPanel Pane3=new JPanel();
JButton button=new JButton("恢复默认");
button.addActionListener(new ActionListener(){
public  void actionPerformed(ActionEvent e){
Print.start_x=50.0d;
Print.start_y=20.0d;
Printout.LineEverypage=80;
Print.interval=10;
LineEveryPage_set.setText("每一页输出 "+80+" 行");
set_x.setText("x坐标的偏移量  x="+50.0);
set_y.setText("y坐标的偏移量 y="+20.0);
setinterval.setText("行与行之间的间距为"+Print.interval);
LineEveryPage_status.setText("默认");
set_x_status.setText("默认");
set_y_status.setText("默认");
setinterval_status.setText("默认");
}
});
Pane3.add(button);
frame.add(Pane3);
}
public void actionPerformed(ActionEvent e){
frame.setVisible(true);//刚开始编记事本的时候直接在这里定义窗口了,导致每一次打开都要定义一次窗口。
//放构造函数定义窗口的好处是不用重复定义,但是弄多了后打开记事本要等久一些。
}//actionPerformed
}//页面设置

//文件->打印
class Printout implements ActionListener{//打印1
public static int LineEverypage=80;    //设置每一页输出多少行,默认80
public void actionPerformed(ActionEvent e){
//获取打印服务对象
String printstr=JLinePrint.editText.getText();
PrinterJob job = PrinterJob.getPrinterJob();
int max_Index=JLinePrint.lineOfC/LineEverypage;
int LeaveLine=JLinePrint.lineOfC-LineEverypage*(max_Index);
job.setPrintable(new Print(printstr,JLinePrint.lineOfC/LineEverypage,LeaveLine));//设置打印类
try {
boolean a=job.printDialog();
//job.getPrintService()获取打印机名字
if(a)
{
int Copies=job.getCopies();
for(int i=-1;++i<Copies;)//打印多少份
{
Print.isFirst=true;
job.print();
}
}//if
}//try
catch (PrinterException e1) {
e1.printStackTrace();
}//catch
}//actionPerformed
}//打印

//使用虚拟打印机SmartPrinterV4
//转载自http://www.blogjava.net/kelly/archive/2007/01/31/96973.html
//需要较大的改动
//在pdf输出排版上需要修改。以及换页命令。
//将文本以'\n'来分成一个String数组,然后一行一行地Graphics.drawString两次,第一次是喷电子,第二次喷墨
//能够设定一页打印多少行,最后LeaveLine小于所设行数,独立出来打印
class Print implements Printable{//Print1
/**
* @param Graphic指明打印的图形环境
* @param PageFormat指明打印页格式(页面大小以点为计量单位,1点为1英才的1/72,1英寸为25.4毫米。A4纸大致为595×842点)
* @param pageIndex指明页号
**/
public static double start_x=50.0d;//设置打印起点的x坐标偏移量
public static double start_y=20.0d;//设置打印起点的y坐标偏移量
public static int interval=10;//设置打印中行与行的间距,默认为10
private int max_pageIndex; //每页输出x行,总共有max_pageIndex页。
private int LeaveLine;//剩余的一页里有多少行
private String str;//传入打印文本
private String temp[];
public static boolean  isFirst;  //用于控制最后一页g2.drawString()执行两次
public static int page;
Print(String str,int max_pageIndex,int LeaveLine){
this.max_pageIndex=max_pageIndex;
this.LeaveLine=LeaveLine;
temp=str.split("\n");
isFirst=true;
}
public int print(Graphics gra, PageFormat pf, int pageIndex) throws PrinterException {
//print string
//转换成Graphics2D
Graphics2D g2 = (Graphics2D) gra;
//设置打印颜色为黑色
g2.setColor(Color.black);

//打印起点坐标
double x = pf.getImageableX();
double y1 = pf.getImageableY();
//设置打印字体(字体名称、样式和点大小)(字体名称可以是物理或者逻辑名称)
//Java平台所定义的五种字体系列:Serif、SansSerif、Monospaced、Dialog 和 DialogInput
Font font = new Font("新宋体", Font.PLAIN, 9);
g2.setFont(font);//设置字体
g2.setColor(FontColour.fontColor);//设置颜色

float heigth = font.getSize2D();//字体高度
double y=y1+1*heigth;
x=x+start_x;
y=y+start_y;
if(pageIndex<max_pageIndex){
int i=Printout.LineEverypage*pageIndex-1;
int len=i+Printout.LineEverypage;
for(;++i<=len;y+=interval)
{
try{
if(temp[i].isEmpty())continue;
}catch(Throwable e){continue;}
g2.drawString(temp[i], (float)x, (float)y);  //这个去掉没有任何输出,用于输出String
}//for
return PAGE_EXISTS;
}//if
//注意这里打印要g2.drawString()两次才能输出
else if(LeaveLine!=0){
if(pageIndex==max_pageIndex){
int i=pageIndex*Printout.LineEverypage-1;
int len=i+LeaveLine;
for(;++i<=len;y+=interval){
if(temp[i].isEmpty())continue;
g2.drawString(temp[i], (float)x, (float)y);  //这个去掉没有任何输出,用于输出String
}
}//if
if(isFirst){
isFirst=false;
return PAGE_EXISTS;
}
else {
LeaveLine=0;
}//else
}//if
return NO_SUCH_PAGE;
}//print
}//Print

//ObjectInputStream和ObjectInputSteam的作用对象
//如果没有implements Serializable接口的话无法保存和读取Object
class Jtext implements Serializable{//序列化
private String SecreteFile;    //密文
public Jtext(String SecreteFile){
this.SecreteFile=SecreteFile;
}
public String getSecreteFile(){
return SecreteFile;
}
}

//加密解码的方式参照了http://blog.csdn.net/zhuxueke_830111/article/details/2009916的记事本加密解密方法
//该例子解密加密的字符默认为'a'和's'
//解密加密方式为        char^char    会变成一个奇怪的字符      即我们看到的密文          再一次       char^char    会恢复成原文
//这个类将每一个密码字符都用于解密加密,且不保存密码,打开时如果密码输入错误会导致解密失败,密文会变成另一段乱码,但是不影响已保存文件的内容
//本例子将JTextField用作密码框,限制输入字符数为10,并使显示字符为 '*' ;
//注意:密文无法使用BufferedWriter类进行保存,需要用ObjectOutputStream类进行保存,否则解密的时候会多出字符
//文件->加密解密
class Encryptdecode implements ActionListener{
private JFrame frame;
private String keyWord;
private int len;
private String s;
public Encryptdecode(){
Menu();
len=0;
s="";
keyWord="";
}//加密解密
public void actionPerformed(ActionEvent e){
frame.setVisible(true);
}//actionPerformed
public void Menu(){
frame=new JFrame("输入密码框");
frame.setBounds(447,190,250,158);
frame.setLayout(null);
frame.setResizable(false);
JLabel label_InputYourKeyWord=new JLabel("请输入密码(限制10个字符)再点击按钮:");
label_InputYourKeyWord.setBounds(10,10,250,20);
final JTextField passWordField=new JTextField(10);
//把文本框改装成密码框,同时实现限制了10个字符的功能
passWordField.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
if(len>=10)passWordField.setText(s);
if(e.getKeyChar()==(char)KeyEvent.VK_BACK_SPACE){
if(len>0){
len--;
s=s.substring(0,len);
keyWord=keyWord.substring(0,len);

}//if
}//if
else if(len<10){
s+="*";//把密码框里的字符全部变为 "*"
len++;
keyWord+=String.valueOf(e.getKeyChar());   //密码用keyWord保存
}//else if
}//keyPressed

public void keyReleased(KeyEvent e1) {
passWordField.setText(s);     //把文本框的内容变为'*'号。
}//keyReleased
public void keyTyped(KeyEvent arg0) {}

});
passWordField.setBounds(20,50,100,30);
JButton button_confirm=new JButton("保存");
button_confirm.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
passWordField.setText(null);//密码框清空
SecretFileSave(Encryption_Decryption(JLinePrint.editText.getText(),keyWord));
len=0;//密码字数重置为0
keyWord="";//密码清空
s="";//密码字符清空
}
});
button_confirm.setBounds(135,50,100,30);
JButton button_Open=new JButton("打开");
button_Open.setBounds(135,90,100,30);
button_Open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
passWordField.setText(null);
SecretFileOpen();
len=0;//密码字数重置为0
keyWord="";//密码清空
s="";//密码字符清空
//把视野转到文本最后面
JLinePrint.editText.setSelectionStart(JLinePrint.editText.getText().length()-2);
JLinePrint.editText.setSelectionEnd(JLinePrint.editText.getText().length()-2);
}
});
frame.addWindowListener(new WindowListener(){

public void windowActivated(WindowEvent arg0) {
//窗口打开的时候
//System.out.println(1);
}

public void windowClosed(WindowEvent arg0) {
//System.out.println(2);
}

public void windowClosing(WindowEvent arg0) {
//窗口关闭的时候
//System.out.println(3);
passWordField.setText(null);
len=0;
keyWord="";
s="";
}

public void windowDeactivated(WindowEvent arg0) {
//窗口关闭的时候
//System.out.println(4);
}

public void windowDeiconified(WindowEvent arg0) {
//System.out.println(5);
}

public void windowIconified(WindowEvent arg0) {
//System.out.println(6);
}

public void windowOpened(WindowEvent arg0) {
//窗口打开的时候
//System.out.println(7);
}

});
frame.add(button_Open);
frame.add(button_confirm);
frame.add(label_InputYourKeyWord);
frame.add(passWordField);
}//Menu
private String Encryption_Decryption(String s,String keyWord){
StringBuffer BF=new StringBuffer(s);
char a=0;
if(keyWord.length()!=0)
{
for(int i=-1;++i<s.length();){
for(int j=-1;++j<keyWord.length();){
a=(char) (s.charAt(i)^keyWord.charAt(j));
}
BF.replace(i, i+1, String.valueOf(a));
}//for
s=BF.toString();
}//if
return s;
}//Encryption
public void SecretFileSave(String s){
try {
FileDialog filedialog=new FileDialog(frame,"加密保存",FileDialog.SAVE);
filedialog.setVisible(true);
Jtext Text=new Jtext(s);
if(filedialog.getDirectory()!=null && filedialog.getFile()!=null){
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(filedialog.getDirectory()+filedialog.getFile()));
out.writeObject(Text);
out.close();
}
}catch(Exception e){}
}//SecretFileSave
public void SecretFileOpen(){
try {
FileDialog filedialog=new FileDialog(frame,"加密打开",FileDialog.LOAD);
filedialog.setVisible(true);
if(filedialog.getDirectory()!=null && filedialog.getFile()!=null){
ObjectInputStream in=new ObjectInputStream(new FileInputStream(filedialog.getDirectory()+filedialog.getFile()));
Jtext Text=(Jtext)in.readObject();
in.close();
String temp=Encryption_Decryption(Text.getSecreteFile(),keyWord);
Textfieldincident.s.push(JLinePrint.editText.getText());
JLinePrint.editText.setText(temp);

}//if
}catch(Exception e1){System.err.println("Error!");}
}//SecretFileOpen
}//加密解密

//文件->退出
class Exit implements ActionListener,WindowListener{
private JFrame frame;
private boolean choose;
private JTextArea editText;
private String path1;
Exit(JFrame frame){
this.frame=frame;
this.editText=JLinePrint.editText;;
path1="";
}
public void actionPerformed(ActionEvent e)
{
//若文件内容有改变,询问用户是否存档
if(Textfieldincident.change){
Save();
}
frame.dispose();
}//actionPerformed
public void Save(){
final String str=editText.getText();//用于输出流时候使用
final JFrame frame=new JFrame("记事本");
frame.setBounds(424, 269, 355, 181);
frame.setLayout(null);
frame.setVisible(true);
JLabel label1=new JLabel("文件的内容已经改变");
label1.setFont(new Font("新宋体",Font.PLAIN,14));
JLabel label2=new JLabel("想保存文件吗?:)");
label2.setFont(new Font("新宋体",Font.PLAIN,14));
label1.setBounds(113,23,180, 23);
label2.setBounds(113,46,180,23);
frame.add(label1);
frame.add(label2);
JButton button_Yes=new JButton("是(Y)");
button_Yes.setMnemonic(KeyEvent.VK_Y);//ALT+Y
button_Yes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e1){
//与另存为相同
choose=false;
FileDialog filedialog=new FileDialog(frame,"另存为",FileDialog.SAVE);
filedialog.setVisible(true);
path1=filedialog.getDirectory()+filedialog.getFile()+".txt";

if(path1.equals("nullnull.txt")||path1.equals(filedialog.getDirectory()+"null.txt"))
{
return;
}//if

final File file=new File(path1);
choose=true;

if( file.exists()){//如果不是第一次保存同时文件重名
choose=false;
final JFrame f=new JFrame("另存为");
f.setBounds(435,276,path1.length()*7+200,125);
f.setVisible(true);
f.setLayout(null);
JLabel label=new JLabel(path1+"已存在。"+"要替换它吗?");
label.setBounds(20,10,path1.length()*7+130,30);
f.add(label);

JButton button_Yes=new JButton("是(Y)");
button_Yes.setMnemonic(KeyEvent.VK_Y);
button_Yes.setBounds(43,58,100,30);
button_Yes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
//若有文件重名时候的文件输出流,输出后直接退出窗口
FileWriter out;
out = new FileWriter(file);
BufferedWriter out_ = new BufferedWriter(out);
String temp[]=str.split("\n");
if (file.canRead()||file.getName()!=null) {
int i=-1;
for(;++i<temp.length-1;){
out_.write(temp[i]);
out_.newLine();
}out_.write(temp[i]);
out_.close();
}//if
editText.setText(null);//把文本框清空
}//try
catch (IOException e3) {
}//catch
f.dispose();

}//actionPerformed
});//ActionListener
f.add(button_Yes);

JButton button_No=new JButton("否(N)");
button_No.setMnemonic(KeyEvent.VK_N);//按ALT+N选择
button_No.setBounds(143+path1.length()*4,58,100,30);
button_No.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
choose=false;
f.dispose();
}
});
f.add(button_No);
}//if
//文件不重名时候的文件输出流
if(choose)
{
//文件输出流
try {
FileWriter out;
out = new FileWriter(file);
BufferedWriter out_ = new BufferedWriter(out);
String temp[]=str.split("\n");
if (file.canRead()||file.getName()!=null) {
int i=-1;
for(;++i<temp.length-1;){
out_.write(temp[i]);
out_.newLine();
}out_.write(temp[i]);
out_.close();
}//if
}//try
catch (IOException e3) {
}//catch
}//if
frame.dispose();
}//actionPerformed
});
JButton button_No=new JButton("否(N)");
button_No.setMnemonic(KeyEvent.VK_N);//按ALT+N选择
button_No.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.dispose();
editText.setText(str);
}//actionPerformed
});
button_Yes.setBounds(81,93,100,30);
button_No.setBounds(211,93,100,30);
frame.add(button_Yes);
frame.add(button_No);
frame.setResizable(false);
}//Save
@Override
public void windowActivated(WindowEvent arg0) {
//窗口初始化
//System.out.println(1);

}
@Override
public void windowClosed(WindowEvent arg0) {
//System.out.println(2);

}
@Override
public void windowClosing(WindowEvent arg0) {
//窗口关闭
//System.out.println(3);
}
@Override
public void windowDeactivated(WindowEvent arg0) {
//窗口最小化
//System.out.println(4);
}
@Override
public void windowDeiconified(WindowEvent arg0) {
//窗口恢复
//System.out.println(5);

}
@Override
public void windowIconified(WindowEvent arg0) {
//窗口隐藏
//System.out.println(6);
}
@Override
public void windowOpened(WindowEvent arg0) {
//窗口打开
//System.out.println(7);

}
}//退出

//编辑->撤销
class Undo implements ActionListener{
public static Stack<String>ss;
Undo(){ss=new Stack<String>();}
public void actionPerformed(ActionEvent arg0) {
if(!Textfieldincident.s.empty()){
String str=Textfieldincident.s.peek();
String str1=JLinePrint.editText.getText();
ss.push(str1);
Textfieldincident.s.pop();
JLinePrint.editText.setText(str);
}//if
else{
String str=JLinePrint.editText.getText();
if(!str.equals(""))ss.push(str);
JLinePrint.editText.setText(null);
}//else
}//actionPerformed
};//撤销

//编辑->恢复
class Recover implements ActionListener{
public void actionPerformed(ActionEvent e){
if(!Undo.ss.empty()){
String str=Undo.ss.peek();
String str1=JLinePrint.editText.getText();
Textfieldincident.s.push(str1);
Undo.ss.pop();
JLinePrint.editText.setText(str);
}//if
}//actionPerformed
}//恢复

//转载自http://zhidao.baidu.com/link?url=_LX5dnt3qCyQgCyLHN4nT7GyXpKpBdRWqCOyX4kzpgikEAcWHGK3MdkTeLRSKCSzMYzmUNYRR81KqxT09bpPwK
//创建一个输出文本行号附带文本框编辑的组件
//加以改动,将repaint方法放在文本框的键盘事件以及打开事件里执行。
//增添了鼠标滑轮事件和拖拽滚动条事件,行框在行数超过1000时改变大小
//增加了文本框鼠标事件,用该事件实现了用鼠标拖拽字符串改变其位置的功能
class JLinePrint extends Panel implements MouseMotionListener,MouseListener{//JJL
public static JTextArea editText;
public JScrollPane RollPane;
public static int pos;//光标在(String)JTextArea.gettext()的位置
public static int lineOfC;//行数
public static int col;//列数
public static boolean refresh;//用于在超过1000行时候刷新
private int fontHeight;//文字字体高度
private int fontWidth;//获得文字字体宽度
public int x;//用于增大行框
public int nowSize;//目前窗口的大小
public static int Mousepos;//获得当前鼠标位置前面的字符个数  ,用于字符串的拖拽
private String s;//用于拖拽字符串到指定位置,用于字符串的拖拽
private boolean isChoosesubstring;//判断是否选择了子串,用于字符串的拖拽
private boolean isClickedsubstring;//判断是否点击了子串,用于字符串的拖拽
private int Start;    //子串的开始位置,用于字符串的拖拽
private int End;      //子串的结束位置,用于字符串的拖拽
public static int X;        //鼠标在文本区域内的X坐标,显示在状态栏里
public static int Y;        //鼠标在文本区域内的Y坐标,显示在状态栏里
public JMenu menu;
public static Point P;     //获得鼠标的坐标
public void repaint_1(){
JLinePrint.this.repaint();
editText.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent arg0) {
try
{
pos=editText.getCaretPosition();
//获取行数
lineOfC=editText.getLineOfOffset(pos)+1;
//获取列数
col=pos-editText.getLineStartOffset(lineOfC-1)+1;
} catch(Exception   e){}
}
});
}
public void setmenu(JMenu menu){
this.menu=menu;
}
public JLinePrint(){
super();   //调用父类的构造函数
P=new Point(0,0);
X=0;
Y=0;
Start=0;
End=0;
isChoosesubstring=false;
isClickedsubstring=false;
nowSize=0;
x=0;
setMinimumSize(new Dimension(30, 30));
setPreferredSize(new Dimension(30,30));//用于修改行框的宽度
editText=new JTextArea(){
public void paint(Graphics g){
super.paint(g);//调用paint方法
}
};
editText.addMouseListener(this);
editText.addMouseMotionListener(this);
RollPane=new JScrollPane(editText);
refresh=false;
RollPane.addMouseWheelListener(new MouseWheelListener(){
//添加鼠标滚轮改变行框事件
@Override
public void mouseWheelMoved(MouseWheelEvent arg0) {
repaint_1();
if(refresh){//行框超过1000行以后行框刷新
setVisible(false);
menu.setVisible(false);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
setVisible(true);
menu.setVisible(true);
refresh=false;
}
}//mouseWheelMoved
});;//addMouseWheelListener
RollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){//监听滚动条事件
@Override
public void adjustmentValueChanged(AdjustmentEvent arg0) {
repaint_1();
if(JLinePrint.refresh){//行框超过1000行以后行框刷新
setVisible(false);
menu.setVisible(false);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}//catch
setVisible(true);
menu.setVisible(true);
refresh=false;
}//if
}//adjustmentValueChanged
});//new AdjustmentListener();
}//JLinePrint()

//重写paint方法
public void paint(Graphics g){
super.paint(g);
//当行数超过1000的时候需要改变行框的宽度
if(lineOfC/1000!=0){
String ss=Integer.toString(lineOfC);
x=(ss.length()-3)*10;
}//if
else{//设置这个的目的是为了当行数超过1000行在回到1000行一下的时候恢复行框原来的宽度
x=0;
}
if(x!=nowSize){
setPreferredSize(new Dimension(30+x,30+x));//用于修改行框的宽度
menu.setPreferredSize(new Dimension(30+x,25));
nowSize=x;
refresh=true;
}
else if(lineOfC/1000==0){   //回到1000行以下恢复行框大小
refresh=false;
}

//JTextArea.viewToModel(Point);  给定的视图坐标系换到最近的模型的位置。    即提供当前视图中的文本位置
//(JViewPoint)JScollPane.getViewPort()  返回滚动视窗
//(Point)JViewPoint.getViewPosition();  返回视图坐标,若无视图返回(0,0);
//start获取的是不在文本框当前视图的滚动条上面的字符个数(包括换行键,换行键算一个字符)
int start=editText.viewToModel(RollPane.getViewport().getViewPosition());
//end获取的是该文本框下所有字符个数(包括换行键,换行键算一个字符)
int end=editText.viewToModel(
new Point(
RollPane.getViewport().getViewPosition().x+editText.getWidth(),
RollPane.getViewport().getViewPosition().y+editText.getHeight()
)
);
Document doc=editText.getDocument();//获取editText的Document类

//AbstactDocument.返回视图依赖的根元素().(java.swing.text.Element)返回子元素指数接近给定的偏移量(int)+1
//startline获取的是当前视图下文本框的第一行是几行
int startline=doc.getDefaultRootElement().getElementIndex(start)+1;

//endline获取的是当前视图下文本框的最后一行是几行
int endline=doc.getDefaultRootElement().getElementIndex(end)+1;

//(Graphics.getFontMetrics(JTextField.getFont())).getHeight()
//获取文本框内字体的高度,用于让行数对应文本框内的文字
fontHeight=(g.getFontMetrics (editText.getFont()).getHeight());
//	fontWidth= (g.getFontMetrics (editText.getFont()).getWidths());

//(Graphics.得到当前字体的字体度量(文本框里的字体)).获得字体的大小
//fontDesc用于校准第一行的1与边框顶端的偏移量
int fontDesc=(g.getFontMetrics(editText.getFont())).getDescent();
int starting_y=-1;
try{
starting_y=editText.modelToView(start).y-RollPane.getViewport().getViewPosition().y+fontHeight-fontDesc;
}

catch(BadLocationException e1){}
for(int line=startline-1,y=starting_y;++line<=endline;y+=fontHeight){
g.drawString(Integer.toString(line), 0, y);
}
}//paint

public void mouseDragged(MouseEvent e) {
if(e.getModifiers()==16){//如果拖动时候使用的是左键
if(isChoosesubstring){
Mousepos=editText.viewToModel(e.getPoint());
editText.setSelectionStart(Mousepos);
editText.setSelectionEnd(Mousepos);
//	System.out.println("选中文件+鼠标拖拽 Start="+Start+" End="+End+" s="+s);
}//if
}//if
}//mouseDragged

public void mouseMoved(MouseEvent e) {
P=e.getPoint();
Mousepos=editText.viewToModel(P);
X=e.getX();   //获取鼠标的X坐标
Y=e.getY();   //获取鼠标的Y坐标
Notepad.status_menubar.setText("Ln:"+JLinePrint.lineOfC+"    Col:"+JLinePrint.col+"    Letters:"+JLinePrint.pos+"      Mousepos="+Mousepos+"     X="+X+"    Y="+Y);//点击鼠标的时候返回光标位置在状态栏里显示
}//mouseDragged

public void mouseClicked(MouseEvent e) {
FindandReplace.First=true;//如果光标位置改变则恢复向上查找的第一次执行以能从最后一个开始遍历。
Notepad.status_menubar.setText("Ln:"+JLinePrint.lineOfC+"    Col:"+JLinePrint.col+"    Letters:"+JLinePrint.pos+"      Mousepos="+Mousepos+"     X="+X+"    Y="+Y);//点击鼠标的时候返回光标位置在状态栏里显示
}

public void mouseEntered(MouseEvent arg0) {
//鼠标进入
//System.out.println(2);

}

public void mouseExited(MouseEvent arg0) {
//鼠标出去
//System.out.println(3);

}

public void mousePressed(MouseEvent e) {
if(e.getModifiers()==16){//左键按下
if(isChoosesubstring){//如果已经选中了一段文本
if(Mousepos>Start && Mousepos<End){//如果鼠标时按下选中的文本上的
isClickedsubstring=true;//那么 “点在文本上” 这个boolean变为true
}//if
else{
isChoosesubstring=false;     //否则,"选中文本"   这个boolean变为false
Start=0;                     //选中文本的始下标变为0
End=0;                       //选中文本的尾下标变为0
}//else
}//if
}//if
}//mousePressed

public void mouseReleased(MouseEvent e) {
//鼠标弹起
if(e.getModifiers()==16){  //左键弹起
//以下两行代码只要弹起左键随时都会执行。
int Start=editText.getSelectionStart();    //获得选中文本的始下标
int End=editText.getSelectionEnd();        //获得选中文本的尾下标
if(Start!=End){
isChoosesubstring=true;
s=editText.getText().substring(Start,End);
this.Start=Start;
this.End=End;
}//if
else if(isClickedsubstring){
if(isClickedsubstring){
editText.replaceRange("", this.Start, this.End);
Mousepos=editText.viewToModel(e.getPoint());
editText.insert(s, Mousepos);
isClickedsubstring=false;
this.Start=0;
this.End=0;
}//if
}//else
}//if
}//mouseReleased
}//JLinePrint

//编辑->即时读档
class Loadstate implements ActionListener{
public Savestate s;
Loadstate(Savestate s){
this.s=s;
}//即时读档
public void actionPerformed(ActionEvent e){
String ss=new String(s.s);
if(!ss.isEmpty())
JLinePrint.editText.setText(ss);
}//actionPerformed
}//即时读档

//编辑->即时存档
class Savestate implements ActionListener{
public String s;
public String time;
public JMenuItem Load;
public Date nowtime;
private int num;
Savestate(JMenuItem Load,int num){
this.Load=Load;
this.num=num;
s=new String();
nowtime=new Date();
}//即时存档
public void actionPerformed(ActionEvent e){
String regex="[.txt]";//正则表达式
if(SaveF.path.equals("")){
JOptionPane.showMessageDialog(new JFrame(), "<html><ul><font face=新宋体 font size=4><i>请保存文件后再使用即时存读档功能。</i></font></ul></html>");
}//if
else{
String Filepath=SaveF.filepath;
String FileName=SaveF.fileName;
FileName=FileName.replaceAll(regex,"");
File file=new File(Filepath+"\\"+FileName+String.valueOf(num)+".txt");//下次打开的时候可以直接读入即时存读档
try {
FileWriter out;
out = new FileWriter(file);
BufferedWriter out_ = new BufferedWriter(out);
String s=JLinePrint.editText.getText();
if (file.canRead()||file.getName()!=null) {
out_.write(nowtime.toString());
out_.newLine();
out_.write(s);
out_.close();
}//if
}//try
catch (IOException e1) {
}//catch
}//else
nowtime=new Date();
time=nowtime.toString();
s=JLinePrint.editText.getText();
((JMenuItem)e.getSource()).setText(time+"      ");
Load.setText(time+"      ");
}//actionPerformed
}//即时存档

//编辑->时间日期
class Timeanddate implements ActionListener{
public void actionPerformed(ActionEvent e){
Date nowtime=new Date();
SimpleDateFormat matter1=new SimpleDateFormat("yyyy'年'MM月dd日HH时mm分ss秒(a)(EE)");
JLinePrint.editText.append(matter1.format(nowtime));
}//actionPerformed
}//时间日期

//编辑->转到
class Gototheline implements ActionListener{
public void actionPerformed(ActionEvent e){
final JFrame frame=new JFrame("转到下列行");
frame.setLayout(new GridLayout(2,1));
frame.setBounds(455,225,249,100);
JPanel pane=new JPanel();
JPanel pane1=new JPanel();
JLabel label=new JLabel("<html><font face='仿宋_GB2312 size=5'>行数:</font></html>");
final JTextField textfield=new JTextField(5);
JButton button=new JButton("确定");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String text=textfield.getText();
if(!text.matches("\\p{Digit}+"))return;//如果输入有非数字则不执行
String[] s=JLinePrint.editText.getText().split("\n");//以回车符切割成String数组
int Position=0;
int EndPosition=Integer.parseInt(text);
if(EndPosition>s.length)EndPosition=s.length;//如果输入的行数大于最大行数则行数等于最大行数
for(int i=0;++i<EndPosition;){//获得指定行数第一个字符在JTextArea.getText()内的位置
Position+=s[i-1].length()+1;
}//for
//起点终点都一样即一个光标
JLinePrint.editText.setSelectionStart(Position);
JLinePrint.editText.setSelectionEnd(Position);
}
});
JButton button1=new JButton("取消");
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.dispose();
}
});
pane.add(label);//行数:
pane.add(textfield);//行数文本框
pane1.add(button);//确定按钮
pane1.add(button1);//取消按钮
frame.add(pane);//行数+行数文本框
frame.add(pane1);//确定+取消按钮
frame.setVisible(true);
frame.setResizable(false);
}//actionPerformed
}//转到

//编辑->剪切
class Cut implements ActionListener{
public static String cut;
public Cut(){
cut=null;
}
public void actionPerformed(ActionEvent e) {
String s=JLinePrint.editText.getText();
int Start=JLinePrint.editText.getSelectionStart();
int End=JLinePrint.editText.getSelectionEnd();
if(Start!=End){
cut=s.substring(Start, End);
JLinePrint.editText.replaceRange("", Start, End);
Copy.copy=false;
}//if
}//actionPerformed
}//剪切

//编辑->复制
class Copy implements ActionListener{
public static boolean copy;
public Copy(){
copy=false;
}//复制
public void actionPerformed(ActionEvent e){
String s=JLinePrint.editText.getText();
int Start=JLinePrint.editText.getSelectionStart();
int End=JLinePrint.editText.getSelectionEnd();
if(Start!=End){
Cut.cut=s.substring(Start, End);
copy=true;
}//if
}
}//复制

//编辑->粘贴
class Paste implements ActionListener{
public void actionPerformed(ActionEvent e){
if(Cut .cut!=null){
int Start=JLinePrint.editText.getSelectionStart();
int End=JLinePrint.editText.getSelectionEnd();
JLinePrint.editText.replaceRange(Cut.cut, Start, End);
if(!Copy.copy)Cut.cut=null;
}//if
}//actionPerformed
}//复制

//编辑->删除
class Delete implements ActionListener{
public void actionPerformed(ActionEvent e){
int Start=JLinePrint.editText.getSelectionStart();
int End=JLinePrint.editText.getSelectionEnd();
JLinePrint.editText.replaceRange("",Start,End);
}//actionPerformed
}//删除

//编辑->查找和替换
class FindandReplace implements ActionListener{
public int Start;
public int End;
public int pos;
public JFrame frame;
public String s;//替换内容
public String p;//子串
public String mainstr;//父串
public boolean isUP;//查找顺序是否为向上,默认为向上
public static boolean First;//用于向上查找
public boolean UpperAndLowerCase;//用于区分大小写,默认为不区分
public boolean Search_Stop;
public FindandReplace(){
p=null;
mainstr="0";
isUP=true;
UpperAndLowerCase=false;
Start=0;
End=0;
Search_Stop=false;
FindMenu();   	//建立菜单
}//查找和替换
public void actionPerformed(ActionEvent e){
if(((JMenuItem)e.getSource()).getText().equals("查找和替换(F)...")){
frame.setVisible(true);
}//e.getSource=="查找";
if(p != null){
if(((JMenuItem)e.getSource()).getText().equals("查找下一个(N)")){
Find();
}//e.getSource().equals(查找下一个);
}//if
}//actionPerformed
public void FindMenu(){
First=true;//用于向上查找
//建立查找窗口
frame=new JFrame("查找和替换");
frame.setBounds(433,347,327,200);
frame.setResizable(false);
frame.setLayout(new FlowLayout());
JLabel label_TheContentForResearching=new JLabel("查找内容(N):");
label_TheContentForResearching.setBounds(8,8,70,8);
final JTextField textfield=new JTextField(10);
textfield.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent e) {
p=((JTextField)e.getSource()).getText();
}
});
textfield.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(p!=null)Find();
}
});
JButton button_searchfornext=new JButton("查找下一个");
button_searchfornext.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(p!=null)Find();
}//actionPerformed
});//addActionListener
JLabel label_TheContentForReplacing=new JLabel("替换内容(C):");
label_TheContentForReplacing.setBounds(8,8,70,8);
final JTextField textfield1=new JTextField(10);
textfield1.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent e) {
s=((JTextField)e.getSource()).getText();
}
});
JButton button_replace=new JButton("替换这一个");
button_replace.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(s!=null){
JLinePrint.editText.replaceRange(s, Start, End);
}
}//actionPerformed
});//addActionListener
JButton button_replaceall=new JButton("替换全部");
button_replaceall.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(p!=null&&s!=null){
JLinePrint.editText.setText(JLinePrint.editText.getText().replaceAll(p, s));
}//if
}//actionPerformed
});//addActionListener
JButton button_change=new JButton("互换");
button_change.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(p!=null&&s!=null){
String temp=p;
textfield.setText(s);
textfield1.setText(temp);
}//if
}
});
JButton button_cancel=new JButton("取消");
button_cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.dispose();
}
});
JCheckBox checkbox=new JCheckBox("区分大小写(C)");
checkbox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(UpperAndLowerCase){
UpperAndLowerCase=false;
}
else{
UpperAndLowerCase=true;
}
}
});
ButtonGroup Direction=new ButtonGroup();
JRadioButton button3=new JRadioButton("向上");
JRadioButton button4=new JRadioButton("向下");
JPanel pane1=new JPanel();

Direction.add(button3);
Direction.add(button4);
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
isUP=true;
}
});
button4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
isUP=false;
}
});
Direction.setSelected(button3.getModel(), true);
UpperAndLowerCase=false; //默认为不区分大小写
pane1.add(button3);
pane1.add(button4);

frame.add(label_TheContentForResearching);//查找内容
frame.add(textfield);                      //查找内容文本框
frame.add(button_searchfornext);           //"查找下一个"按钮

frame.add(label_TheContentForReplacing);  //替换内容
frame.add(textfield1);                    //替换内容文本框
frame.add(button_replace);                //"替换这一个"按钮

frame.add(checkbox);                //区分大小写

frame.add(pane1);                 //方向
//设置方向文本框
pane1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("方向"),BorderFactory.createEmptyBorder()));

frame.add(button_cancel);        //取消按钮
frame.add(button_change);        //互换按钮
frame.add(button_replaceall);     //替换全部按钮
}//FindMenu
public void Find(){
mainstr=JLinePrint.editText.getText();
int[] next=new int[p.length()];
if(isUP){//如果选择了向上查找
//向上查找
//若pos=JLinePrint.pos只有这句的话会卡在最后一个没办法继续向上查找
//若pos=JLinePrint.pos-1只有这句的话会跳过最后一个只从倒数第二个开始执行
if(First){
pos=JLinePrint.pos;//UP获取光标位置
First=false;
}//if
else {
pos=JLinePrint.pos-1;
if(pos<=1)First=true;
}//else
getNext_UP(p,next);
if(!UpperAndLowerCase){ //是否区分大小写
KMPFind_UP_UpperAndLowerCase(mainstr,p,next,pos);
}
else{
KMPFind_UP(mainstr,p,next,pos);
}
//选择Start位置和End位置之间的文本
JLinePrint.editText.setSelectionStart(Start);
JLinePrint.editText.setSelectionEnd(End);
}//if
else//向下查找
{
pos=JLinePrint.pos+1;//DOWN获取光标位置
getNext_DOWN(p,next);
if(!UpperAndLowerCase){ //是否区分大小写
KMPFind_DOWN_UpperAndLowerCase(mainstr,p,next,pos);
}//if
else
{
KMPFind_DOWN(mainstr,p,next,pos);
}//else
//选择Start位置和End位置之间的文本
JLinePrint.editText.setSelectionStart(Start);
JLinePrint.editText.setSelectionEnd(End);
}//else
}//Find
public void KMPFind_DOWN_UpperAndLowerCase(String mainstr,String p,int[] next,int pos){//向下查找,不区分大小写
int i=pos,j=1;
while(i<=mainstr.length()&&j<=p.length()){
//	str=String.valueOf(mainstr.charAt(i-1));
//	str1=String.valueOf(p.charAt(j-1));
if(j==0||judge(i-1,j-1)){
i++;
j++;
}//if
else{
j=next[j-1]+1;
}
}//while
if(j>p.length()){
Start=i-p.length()-1;
End=Start+p.length();
}
else{
Search_Stop=true;
JOptionPane.showMessageDialog(new JFrame(), "已完成对文档下半部分的搜索");
Start=0;End=0;
}
}//KMPFind_DOWN_UpperAndLowerCase
public void KMPFind_UP_UpperAndLowerCase(String mainstr,String p,int[] next,int pos){//向上查找,不区分大小写
int length=p.length()-1;
int i=pos-1,j=length;
while(i>-1 && j>-1){
if(j==length+1||judge(i,j)){
i--;
j--;
}//if
else{
j=next[j];
}
}//while
if(j<=-1){
End=i+p.length()+1;
Start=End-p.length();
}
else{
JOptionPane.showMessageDialog(new JFrame(), "已完成对文档上半部分的搜索");
Start=mainstr.length();
End=mainstr.length();
First=true;
}
}//KMPFind_UP_UpperAndLowerCase
public void KMPFind_DOWN(String mainstr,String p,int[] next,int pos){//pos为当前光标所在位置,向下查找,区分大小写
int i=pos,j=1;
while(i<=mainstr.length()&&j<=p.length()){
if(j==0||mainstr.charAt(i-1)==p.charAt(j-1)){
i++;
j++;
}//if
else{
j=next[j-1]+1;
}
}//while
if(j>p.length()){

Start=i-p.length()-1;
End=Start+p.length();
}
else{
Search_Stop=true;
JOptionPane.showMessageDialog(new JFrame(), "已完成对文档下半部分的搜索");
Start=0;End=0;
}
}//KMP
public void KMPFind_UP(String mainstr,String p,int[] next,int pos){//pos为当前光标所在位置,向上查找,区分大小写
int length=p.length()-1;
int i=pos-1,j=length;
while(i>-1 && j>-1){
if(j==length+1||mainstr.charAt(i)==p.charAt(j)){
i--;
j--;
}//if
else{
j=next[j];
}
}//while
if(j<=-1){
End=i+p.length()+1;
Start=End-p.length();
}
else{
JOptionPane.showMessageDialog(new JFrame(), "已完成对文档上半部分的搜索");
Start=mainstr.length();
End=mainstr.length();
First=true;
}
}//KMP
public void getNext_DOWN(String p,int[] next){//pos为当前光标所在位置
int i=0,j=-1;next[0]=-1;
while(i<p.length()-1){
if(j==-1||p.charAt(i)==p.charAt(j)){
i++;
j++;
next[i]=j;
}//if
else j=next[j];
}//while
}//getNext
public void getNext_UP(String p,int[] next){//pos为当前光标所在位置
int length=p.length()-1;
int i=length,j=length+1;next[length]=length+1;
while(i>0){
if(j==length+1||p.charAt(i)==p.charAt(j)){
i--;
j--;
next[i]=j;
}//if
else j=next[j];
}//while
}//getNext
public boolean judge(int i,int j){
String str1=String.valueOf(p.charAt(j));
if(str1.matches("[a-zA-Z]")){
String str=String.valueOf(mainstr.charAt(i));
String str3="("+str1.toLowerCase()+"|"+str1.toUpperCase()+")";
return str.matches(str3);
}
else{
return mainstr.charAt(i)==p.charAt(j);
}
}//judge
}//查找

//编辑->全选
class Choosetheall implements ActionListener{
public void actionPerformed(ActionEvent e){
JLinePrint.editText.selectAll();
}//actionPerformed
}//全选

//格式->字体
class Fontf implements ActionListener{
private JFrame frame;
private String[] fonts;//字体样式
private String[] fonts_appearance;//字体形状
private String[] fonts_size;//字体大小
public static String font;//选中的字体样式
public static int font_appearance;//选中的字体形状
public static int font_size;//选中的字体大小
private int[] sizeVal;	//字体大小匹配值
private HashMap hashmap;//哈斯映射图
private String ex;//实例
private JTextArea Example_display;//实例文本区域
private JList list_font;
private JTextField textfield_font;
private JList list_appearance;
private JTextField textfield_appearance;
private JList list_fontsize;
private JTextField textfield_fontsize;
private boolean isInput;//定义一个boolean来避免在文本框输入字体时候报错
public Fontf(){
//文本框默认字体
font="新宋体";
font_appearance=Font.PLAIN;
font_size=15;
isInput=false;
hashmap=new HashMap(16);
fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); // 返回系统所有可用字体
String[] fonts_appearance={"常规","粗体","斜体","粗斜体"};
String[] fonts_size={ "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72",
"初号", "小初", "一号", "小一", "二号", "小二", "三号", "小三", "四号", "小四", "五号", "小五",
"六号", "小六", "七号", "八号"};
int[] sizeVal = {8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72, 42, 36, 26, 24, 22, 18, 16, 15, 14, 12, 11, 9, 8, 7, 6, 5};
for(int i=15;++i<32;){
hashmap.put(fonts_size[i],sizeVal[i]);
}
this.fonts_appearance=fonts_appearance;
this.fonts_size=fonts_size;
this.sizeVal=sizeVal;
FontMenu();
list_font.setSelectedValue(font, true);
textfield_appearance.setText("常规");
list_appearance.setSelectedValue("常规",true);
textfield_fontsize.setText("15");
}
public void actionPerformed(ActionEvent e){
ex=JLinePrint.editText.getText();
int Start=JLinePrint.editText.getSelectionStart();
int End=JLinePrint.editText.getSelectionEnd();
if(Start!=End)ex=ex.substring(Start, End);
else ex="微软AaBbTyZz";
Example_display.setText(ex);
frame.setVisible(true);
}//actionPerformed
public void FontMenu(){
frame=new JFrame("字体");
frame.setBounds(426,258,490,318);
frame.setLayout(null);

//字体 样式
JLabel label_font=new JLabel("字体(F):");
label_font.setBounds(10,5,142,15);
//字体文本框
textfield_font=new JTextField(10);
textfield_font.setBounds(10,20,150,20);
//设置文本框输入也能改变字体样式
textfield_font.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent arg0) {
font=textfield_font.getText();
list_font.setSelectedValue(font, true);
isInput=true;
}
});
//字体选择器
list_font=new JList(fonts);
JScrollPane list_font_scroll=new JScrollPane(list_font);
list_font.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
font=(String)list_font.getSelectedValue();
if(!isInput)
textfield_font.setText(font);
else
isInput=false;
Example_display.setFont(new Font(font,font_appearance,font_size));
}
});
list_font_scroll.setBounds(10,40,150,100);
//窗口添加字体
frame.add(label_font);   //字体(F);
frame.add(textfield_font); //字体文本框
frame.add(list_font_scroll);//字体选择器
//字体形状
JLabel label_appearance=new JLabel("字形(Y):");
label_appearance.setBounds(170,5,142,15);
//字形文本框
textfield_appearance=new JTextField(10);
textfield_appearance.setBounds(170,20,150,20);
//设置文本框输入也能改变字体形状
textfield_appearance.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent arg0) {
String temp=textfield_appearance.getText();
for(int i=-1;++i<4;){
if(fonts_appearance[i].equals(temp)){
font_appearance=i;
break;
}
}//for
list_appearance.setSelectedValue(temp, true);
isInput=true;
}//caretUpdata

});
//字形选择器
list_appearance=new JList(fonts_appearance);
JScrollPane list_fontsappearance_scroll=new JScrollPane(list_appearance);
list_fontsappearance_scroll.setBounds(170,40,150,100);
list_appearance.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent arg0) {
font_appearance=list_appearance.getSelectedIndex();
String temp=(String)list_appearance.getSelectedValue();
//常规Font.PLAIN 0 粗体BOLD 1 斜体ITALIC 2 粗斜体BOLD+ITALIC 3
if(!isInput)textfield_appearance.setText(temp);
else isInput=false;
Example_display.setFont(new Font(font,font_appearance,font_size));
}
});
//窗口添加字形
frame.add(label_appearance);//字形(Y):
frame.add(textfield_appearance);//字形文本框
frame.add(list_fontsappearance_scroll);//字形选择器
//字体大小
JLabel label_fontsize=new JLabel("大小(S):");
label_fontsize.setBounds(330,5,50,15);
//字体大小文本框
textfield_fontsize=new JTextField(5);
textfield_fontsize.setBounds(330,20,60,20);
//设置文本框输入也能改变字体大小
textfield_fontsize.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent arg0) {
String temp=textfield_fontsize.getText();
String regex="[0-9]{1,4}";//限制大小在一位数到四位数之间
if(temp.matches(regex)){
font_size=Integer.parseInt(temp);
isInput=true;
list_fontsize.setSelectedValue(temp, true);
Example_display.setFont(new Font(font,font_appearance,font_size));
}//if
else{
if(hashmap.get(temp)!=null)font_size=(int) hashmap.get(temp);
isInput=true;
list_fontsize.setSelectedValue(temp, true);
Example_display.setFont(new Font(font,font_appearance,font_size));
}//else
}//caretUpdate

});
//字体大小选择器
list_fontsize=new JList(fonts_size);
JScrollPane list_fontsize_scroll=new JScrollPane(list_fontsize);
list_fontsize_scroll.setBounds(330,40,60,100);
list_fontsize.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent arg0){
String temp=(String)list_fontsize.getSelectedValue();
int index=list_fontsize.getSelectedIndex();
font_size=sizeVal[index];
if(!isInput)
textfield_fontsize.setText(temp);
else isInput=false;
Example_display.setFont(new Font(font,font_appearance,font_size));
}
});
//窗口添加字体大小
frame.add(label_fontsize);//字体大小
frame.add(textfield_fontsize);//字体大小文本框
frame.add(list_fontsize_scroll);//字体大小选择器
//确定按钮
JButton Confirm=new JButton("确定");
Confirm.setBounds(404,20,70,23);
Confirm.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JLinePrint.editText.setFont(new Font(font,font_appearance,font_size));
frame.dispose();
}
});
frame.add(Confirm);
//取消按钮
JButton Cancel=new JButton("取消");
Cancel.setBounds(404,50,70,23);
Cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.dispose();
}
});
frame.add(Cancel);

//实例显示:
JLabel Example=new JLabel("实例:");
Example.setBounds(10,150,100,15);
frame.add(Example);

Example_display=new JTextArea();
Example_display.setBounds(10,170,380,112);
Example_display.setEditable(false);
frame.add(Example_display);
}//FontMenu
}//字体

//格式->字体颜色
class FontColour implements ActionListener{
public static Color fontColor;
FontColour(){
fontColor=Color.black;
}//字体颜色
public void actionPerformed(ActionEvent e) {
fontColor=JColorChooser.showDialog(new JFrame(), "字体颜色", JLinePrint.editText.getForeground());
JLinePrint.editText.setForeground(fontColor);
}//actionPerformed
}//字体颜色

//格式->背景颜色
class BackgroundColour implements ActionListener{
public static Color BackGroundColor;
BackgroundColour(){
BackGroundColor=Color.white;
}
public void actionPerformed(ActionEvent e){
BackGroundColor=JColorChooser.showDialog(new JFrame(), "背景颜色", JLinePrint.editText.getBackground());
JLinePrint.editText.setBackground(BackGroundColor);
}
}//背景颜色

class Textfieldincident implements KeyListener{//文本框事件1
public static boolean change;//用于判断文本框是否改变
private JLinePrint lineprint;
private JMenu menu;
public static int i;//用来统计键入字符的个数
public static int max_String; //定义键入字符数量,当达到这一数量时候文本入栈,默认为10
public static Stack<String> s;
String regex;//正则表达式
Textfieldincident(JLinePrint lineprint,JMenu menu){
change=false;
this.lineprint=lineprint;
this.menu=menu;
max_String=10; // 默认为10
i=0;
s=new Stack<String>();
regex=new String("[^\\W]");//正则表达式
}//文本框事件
public void keyPressed(KeyEvent e) {
change=true;
lineprint.repaint_1();
}//keyPressed

public void keyReleased(KeyEvent e1) {
//如果把行框刷新放在keyPressed里需要下次出现文本框事件的时候才能执行行框刷新
//而把行框刷新放在keyReleased里可以在按键弹出的时候执行,即在当前文本框事件就能进行行框刷新
//PS:keyPressed键盘按下   keyReleased键盘弹起    keyTyped键盘按下并弹起
if(JLinePrint.refresh){//行框超过1000行以后行框刷新,行框超过1000行会遮住最后一个数字
lineprint.setVisible(false);
menu.setVisible(false);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
lineprint.setVisible(true);
menu.setVisible(true);
JLinePrint.refresh=false;
}//if
//用于撤销
String ss=String.valueOf(e1.getKeyChar());
if(ss.matches(regex)){//如果输入的是字符的话
if(i++==max_String){//达到10个字符以后入栈一次
i=0;
String canceltext=JLinePrint.editText.getText();
s.push(canceltext);
}//if
}//if
}//keyReleased

public void keyTyped(KeyEvent e2) {
//列的计算有些问题,把\t算作一个字符了;
JLinePrint.Mousepos=JLinePrint.editText.viewToModel(JLinePrint.P);
Notepad.status_menubar.setText("Ln:"+JLinePrint.lineOfC+"    Col:"+JLinePrint.col+"    Letters:"+JLinePrint.pos+"      Mousepos="+JLinePrint.Mousepos+"     X="+JLinePrint.X+"    Y="+JLinePrint.Y);//点击鼠标的时候返回光标位置在状态栏里显示
}
}//文本框事件

class AboutNotpad implements ActionListener{
private JFrame frame;
AboutNotpad(){
Menu();
}
public void actionPerformed(ActionEvent e){
frame.setVisible(true);
}
public void Menu(){
frame=new JFrame("关于");
frame.setLayout(null);
frame.setBounds(465,251,358,173);
JLabel label=new JLabel("<html><br><img width=100 height=100 src=\"http://ico.ooopic.com/ajax/iconpng/?id=160683.png\"></br></html>");
label.setBounds(10,10,100,120);
JLabel author=new JLabel("By @author wuwave");
author.setBounds(153,47,200,20);
JLabel useTime=new JLabel("所用时间:");
useTime.setBounds(153,70,200,20);
useTime.setFont(new Font("新宋体",Font.BOLD,15));
JLabel time=new JLabel("2014.11.4-2014.11.18");
time.setFont(new Font("新宋体",Font.BOLD,15));
time.setBounds(153,90,200,20);
frame.add(label);
frame.add(author);
frame.add(useTime);
frame.add(time);
frame.setResizable(false);
}
}//关于

//帮助主题
class Helpp implements ActionListener,TreeSelectionListener{
private JTree Tree;
private JFrame frame;
private JTextArea textArea;
private JScrollPane scrollpane;
private String TreeNode_Notepad[];
private String Contents[];
private HashMap hashmap;
public Helpp(){
Menu();
ReadContent();
}
public void ReadContent(){
File file=new File("D:\\帮助文档.txt");
Contents=new String[31];//这里之所以是31个,多了一个是因为父节点不包含在子节点里面,父节点有一个,子节点有三十个
if(file.canRead()){
try {
FileReader FIS=new FileReader(file);
BufferedReader in=new BufferedReader(FIS);
String s=in.readLine();
s=in.readLine();
String temp;
for(int i=-1;++i<31;){
temp="";
while(!s.equals("End")){
temp+=s+'\n';
s=in.readLine();
}//while
s=in.readLine();
s=in.readLine();
Contents[i]=temp;
}//for
} catch (IOException e) {
e.printStackTrace();
}//catch
}//if
else{
for(int i=-1;++i<31;)
{
Contents[i]="找不到D:\\帮助文档.txt";
textArea.setForeground(Color.red);
}
}
}//ReadContent
public void actionPerformed(ActionEvent e){
frame.setVisible(true);
}
public void Menu(){
frame=new JFrame("帮助主题");
frame.setLayout(new BorderLayout());
frame.setBounds(300,57,729,646);
textArea=new JTextArea();
scrollpane=new JScrollPane(textArea);
textArea.setSize(200,100);
textArea.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black), BorderFactory.createEmptyBorder()));
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.WHITE);
textArea.setFont(new Font("新宋体",Font.PLAIN,15));
textArea.setLineWrap(true);
DefaultMutableTreeNode Notepad=new DefaultMutableTreeNode("记事本");
Tree=new JTree(Notepad);
Tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
Tree.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black), BorderFactory.createEmptyBorder()));
Tree.addTreeSelectionListener(this);
frame.add(Tree,BorderLayout.WEST);
frame.add(scrollpane,BorderLayout.CENTER);
textArea.setEditable(false);
//创建哈斯图
//哈斯图用来建立一一映射的关系,在这里用于调用指定的文本
hashmap=new HashMap(31);
//创建记事本分节点
String[]TreeNode_Notepad1={"新建类","打开类","保存类","页面设置类","打印类","Print类","Jtext类","加密解密类","退出类","撤销类","恢复类","JLinePrint类",
"即时读档类","即时存档类","时间日期类","转到类","剪切类","复制类","粘贴类","删除类","查找和替换类","全选类","字体类","字体颜色类",
"背景颜色类","文本框事件类","文本框鼠标事件类","关于记事本类","帮助主题类","Notepad类"};
this.TreeNode_Notepad=TreeNode_Notepad1;
DefaultMutableTreeNode[] TreeNode_Notepad =new DefaultMutableTreeNode[30];
hashmap.put("记事本", 0);
for(int i=-1;++i<30;){
TreeNode_Notepad[i]=new DefaultMutableTreeNode(TreeNode_Notepad1[i]);
Notepad.add(TreeNode_Notepad[i]);
hashmap.put(TreeNode_Notepad1[i], i+1);
}//for
}//Menu

public void valueChanged(TreeSelectionEvent arg0) {
//获取被选中的节点
DefaultMutableTreeNode node = (DefaultMutableTreeNode)Tree.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
//   System.out.println(Contents[(int) hashmap.get((String)nodeInfo)+1]);
textArea.setText(Contents[(int) hashmap.get((String)nodeInfo)]);
textArea.setSelectionStart(0);
textArea.setSelectionEnd(0);

}
}//帮助主题

public class Notepad{//NNotepad
public static boolean LineDisplay=false;//显示行数
public static boolean StatusBar=false;//状态栏是否显示
public static boolean AutoChangeLine=true;//自动换行
public static JTextArea status_menubar;//状态栏
public static Loadstate Load[];//用于在打开中获得数据
public static Savestate Save[];//用于在打开中获得数据
public static JMenuItem Load_subMenu[];//用于在打开中获得标签
public static JMenuItem Save_subMenu[];//用于在打开中获得标签
private static void Menu_File(JMenuBar menubar,JFrame frame,JLinePrint lineprint) {
// 菜单:文件
JMenu Menu_file = new JMenu("文件(F)");
Menu_file.setMnemonic(KeyEvent.VK_F);
menubar.add(Menu_file);
// 菜单项:新建
NewC new_ = new NewC();
JMenuItem menuitem_new = new JMenuItem("新建(N)");
menuitem_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
menuitem_new.setMnemonic(KeyEvent.VK_N);
menuitem_new.addActionListener(new_);
Menu_file.add(menuitem_new);
// 菜单项:打开
OpenF open = new OpenF(frame,lineprint);
JMenuItem menuitem_open = new JMenuItem("打开(O)...");
menuitem_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
menuitem_open.setMnemonic(KeyEvent.VK_O);
menuitem_open.addActionListener(open);
Menu_file.add(menuitem_open);
// 菜单项:保存
SaveF save=new SaveF(frame);
JMenuItem menuitem_save = new JMenuItem("保存(S)");
menuitem_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
menuitem_save.setMnemonic(KeyEvent.VK_S);
menuitem_save.addActionListener(save);
Menu_file.add(menuitem_save);
// 菜单项:另存为
SaveF resave=new SaveF(frame);//保存和另存为的ActionListener放在同一个类里面
JMenuItem menuitem_resave = new JMenuItem("另存为(A)...");
menuitem_resave.setMnemonic(KeyEvent.VK_A);
menuitem_resave.addActionListener(resave);
Menu_file.add(menuitem_resave);
// 分隔线
Menu_file.addSeparator();
// 菜单项:页面设置
JMenuItem menuitem_pagesetup = new JMenuItem("页面设置(U)...");
PageSetting pagesetup=new PageSetting();
menuitem_pagesetup.setMnemonic(KeyEvent.VK_U);
menuitem_pagesetup.setEnabled(true);
menuitem_pagesetup.addActionListener(pagesetup);
Menu_file.add(menuitem_pagesetup);
// 菜单项:打印
JMenuItem menuitem_print = new JMenuItem("打印(P)...");
Printout print=new Printout();
menuitem_print.setMnemonic(KeyEvent.VK_P);
menuitem_print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_MASK));
menuitem_print.addActionListener(print);
Menu_file.add(menuitem_print);
//分隔线
Menu_file.addSeparator();
//菜单项:加密解密
Encryptdecode encryption=new Encryptdecode();
JMenuItem menuitem_encryption=new JMenuItem("加密解密(E)");
menuitem_encryption.setMnemonic(KeyEvent.VK_E);
menuitem_encryption.addActionListener(encryption);
Menu_file.add(menuitem_encryption);
//分隔线
Menu_file.addSeparator();
// 菜单项:退出
Exit exit=new Exit(frame);
JMenuItem menuitem_exit = new JMenuItem("退出(X)");
menuitem_exit.setMnemonic(KeyEvent.VK_X);
menuitem_exit.addActionListener(exit);
Menu_file.add(menuitem_exit);
frame.addWindowListener(exit);
}// Menu_File

private static void Menu_Edit(JMenuBar menubar) {
// 菜单:编辑
JMenu Menu_edit = new JMenu("编辑(E)");
Menu_edit.setMnemonic(KeyEvent.VK_E);
menubar.add(Menu_edit);
// 菜单项:撤销
Undo cancel=new Undo();
JMenuItem menu_revocation = new JMenuItem("撤销(U)");
menu_revocation.setMnemonic(KeyEvent.VK_U);
menu_revocation.addActionListener(cancel);
menu_revocation.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_MASK));
Menu_edit.add(menu_revocation);
//菜单项:恢复
Recover recover=new Recover();
JMenuItem menu_recover = new JMenuItem("恢复");
menu_recover.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y,InputEvent.CTRL_MASK));
menu_recover.addActionListener(recover);
Menu_edit.add(menu_recover);
//菜单项:清空文本
JMenuItem menu_setnull=new JMenuItem("清空文本(H)");
menu_setnull.setMnemonic(KeyEvent.VK_H);
menu_setnull.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Textfieldincident.s.push(JLinePrint.editText.getText());
JLinePrint.editText.setText(null);
}
});
Menu_edit.add(menu_setnull);
//菜单项:即时存档Write snapshot
JMenu menu_Write_snapshot=new JMenu("即时存档(W)");
menu_Write_snapshot.setMnemonic(KeyEvent.VK_W);
Menu_edit.add(menu_Write_snapshot);
//即时存档子菜单
Save_subMenu=new JMenuItem[10];

Save=new Savestate [10];
Load=new Loadstate[10];

int j=KeyEvent.VK_F1;
JMenu menu_Load_snapshot=new JMenu("即时读档(L)");
menu_Load_snapshot.setMnemonic(KeyEvent.VK_L);
Menu_edit.add(menu_Load_snapshot);
//即时读档子菜单
Load_subMenu=new JMenuItem[10];
j=KeyEvent.VK_F1;
for(int i=-1;++i<10;){
Save_subMenu[i]=new JMenuItem("--------/--------     ");
Save_subMenu[i].setAccelerator(KeyStroke.getKeyStroke(j,InputEvent.SHIFT_MASK));
menu_Write_snapshot.add(Save_subMenu[i]);

Load_subMenu[i]=new JMenuItem("--------/--------     ");
Load_subMenu[i].setAccelerator(KeyStroke.getKeyStroke(j++,0));
menu_Load_snapshot.add(Load_subMenu[i]);

Save[i]=new Savestate(Load_subMenu[i],i+1);//i+1识别编号
Load[i]=new Loadstate(Save[i]);

Save_subMenu[i].addActionListener(Save[i]);
Load_subMenu[i].addActionListener(Load[i]);
}//for
// 分隔线
Menu_edit.addSeparator();
// 菜单项:剪切
Cut cut=new Cut();
JMenuItem menu_cut = new JMenuItem("剪切(T)");
menu_cut.setMnemonic(KeyEvent.VK_T);
menu_cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));
menu_cut.addActionListener(cut);
Menu_edit.add(menu_cut);
// 菜单项:复制
Copy copy=new Copy();
JMenuItem menu_copy = new JMenuItem("复制(C)");
menu_copy.setMnemonic(KeyEvent.VK_C);
menu_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));
menu_copy.addActionListener(copy);
Menu_edit.add(menu_copy);
// 菜单项:粘贴
Paste paste=new Paste();
JMenuItem menu_paste = new JMenuItem("粘贴(P)");
menu_paste.setMnemonic(KeyEvent.VK_P);
menu_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));
menu_paste.addActionListener(paste);
Menu_edit.add(menu_paste);
// 菜单项:删除L Del
Delete Delete=new Delete();
JMenuItem menu_delete = new JMenuItem("删除(L)");
menu_delete.setMnemonic(KeyEvent.VK_L);
menu_delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
menu_delete.addActionListener(Delete);
Menu_edit.add(menu_delete);
// 分隔线
Menu_edit.addSeparator();
// 菜单项:查找F... F
FindandReplace FindAndChange=new FindandReplace();
JMenuItem menu_search = new JMenuItem("查找和替换(F)...");
menu_search.setMnemonic(KeyEvent.VK_F);
menu_search.addActionListener(FindAndChange);
menu_search.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_MASK));
Menu_edit.add(menu_search);
// 菜单项:查找下一个N F3
JMenuItem menu_searchfornext = new JMenuItem("查找下一个(N)");
menu_searchfornext.setMnemonic(KeyEvent.VK_N);
menu_searchfornext.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0));
menu_searchfornext.addActionListener(FindAndChange);
Menu_edit.add(menu_searchfornext);
// 菜单项:转到G... G
JMenuItem menu_goto = new JMenuItem("转到(G)");
Gototheline goto_=new Gototheline();
menu_goto.setMnemonic(KeyEvent.VK_G);
menu_goto.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,InputEvent.CTRL_MASK));
menu_goto.addActionListener(goto_);
Menu_edit.add(menu_goto);
// 分隔线
Menu_edit.addSeparator();
// 菜单项:全选A A
Choosetheall SelectAll=new Choosetheall();
JMenuItem menu_selectall = new JMenuItem("全选(A)");
menu_selectall.setMnemonic(KeyEvent.VK_A);
menu_selectall.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
menu_selectall.addActionListener(SelectAll);
Menu_edit.add(menu_selectall);
// 菜单项:时间日期D F5
JMenuItem menu_timedate = new JMenuItem("时间日期(D)");
Timeanddate TimeAndDate=new Timeanddate();
menu_timedate.setMnemonic(KeyEvent.VK_D);
menu_timedate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0));
menu_timedate.addActionListener(TimeAndDate);
Menu_edit.add(menu_timedate);
}//Menu_file

private static void Menu_format(JMenuBar menubar) {
// 菜单:格式O
JMenu Menu_edit = new JMenu("格式(O)");
Menu_edit.setMnemonic(KeyEvent.VK_O);
menubar.add(Menu_edit);
// 菜单项:自动换行W
JMenuItem menu_AUTO_changline = new JMenuItem("自动换行(W)");
menu_AUTO_changline.setMnemonic(KeyEvent.VK_W);
menu_AUTO_changline.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JLinePrint.editText.setLineWrap(AutoChangeLine);
if(AutoChangeLine){
AutoChangeLine=false;
((JMenuItem)e.getSource()).setText("自动换行(W) √");
}
else{
AutoChangeLine=true;
((JMenuItem)e.getSource()).setText("自动换行(W)");
}
}
});
Menu_edit.add(menu_AUTO_changline);
//分隔线
Menu_edit.addSeparator();
// 菜单项:字体F...
Fontf _Font=new Fontf();
JMenuItem menu_fonts = new JMenuItem("字体(F)...");
menu_fonts.setMnemonic(KeyEvent.VK_F);
menu_fonts.addActionListener(_Font);
Menu_edit.add(menu_fonts);
//菜单项:字体颜色C...
FontColour FontColor=new FontColour();
JMenuItem menu_FontColor=new JMenuItem("字体颜色(C)...");
menu_FontColor.setMnemonic(KeyEvent.VK_C);
menu_FontColor.addActionListener(FontColor);
Menu_edit.add(menu_FontColor);
//菜单项:背景颜色B...
BackgroundColour BackGround_Color=new BackgroundColour();
JMenuItem menu_BackGroundColor=new JMenuItem("背景颜色(B)...");
menu_BackGroundColor.setMnemonic(KeyEvent.VK_B);
menu_BackGroundColor.addActionListener(BackGround_Color);
Menu_edit.add(menu_BackGroundColor);
}//Menu_format

private static void Menu_examine(JMenuBar menubar,final JLinePrint lineprint,final JMenu menu,JFrame frame) {
// 菜单:查看V
JMenu Menu_examine = new JMenu("查看(V)");
Menu_examine.setMnemonic(KeyEvent.VK_V);
menubar.add(Menu_examine);
//状态栏
status_menubar=new JTextArea();
status_menubar.setBackground(new Color(255,255,224));//getHSBColor色调-饱和度-亮度
status_menubar.setEditable(false);
status_menubar.setText("Ln:"+JLinePrint.lineOfC+"    Col:"+JLinePrint.col+"    Letters:"+JLinePrint.pos);
frame.add(status_menubar,BorderLayout.SOUTH);
// 菜单项:状态栏S
JMenuItem menu_StatusBar = new JMenuItem("状态栏(S) √");
menu_StatusBar.setMnemonic(KeyEvent.VK_S);
menu_StatusBar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e1){
status_menubar.setVisible(StatusBar);
if(!StatusBar){
((JMenuItem)e1.getSource()).setText("状态栏(S)");
StatusBar=true;
}
else{
((JMenuItem)e1.getSource()).setText("状态栏(S) √");
StatusBar=false;
}
}
});
Menu_examine.add(menu_StatusBar);
//菜单项:显示行数L
JMenuItem menu_DisplayLine = new JMenuItem("显示行数(L) √");
menu_DisplayLine.setMnemonic(KeyEvent.VK_L);
menu_DisplayLine.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
lineprint.setVisible(LineDisplay);
menu.setVisible(LineDisplay);
if(!LineDisplay){
((JMenuItem)e.getSource()).setText("显示行数(L)");
LineDisplay=true;
}//if
else {
((JMenuItem)e.getSource()).setText("显示行数(L) √");
LineDisplay=false;
}//else
}//actionPerformed
});//ActionListener
Menu_examine.add(menu_DisplayLine);

}//Menu_examine

private static void Menu_Help(JMenuBar menubar) {
// 菜单:帮助H
JMenu Menu_help = new JMenu("帮助(H)");
Menu_help.setMnemonic(KeyEvent.VK_H);
menubar.add(Menu_help);
// 菜单项:帮助主题H
Helpp Help=new Helpp();
JMenuItem menu_HelpTopics = new JMenuItem("帮助主题(H)");
menu_HelpTopics.setMnemonic(KeyEvent.VK_H);
menu_HelpTopics.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, KeyEvent.ALT_DOWN_MASK));
menu_HelpTopics.addActionListener(Help);
Menu_help.add(menu_HelpTopics);
// 分隔线
Menu_help.addSeparator();
// 菜单项:关于记事本(A)
AboutNotpad AboutTheNotePad=new AboutNotpad();
JMenuItem menu_aboutnotepad = new JMenuItem("关于记事本(A)");
menu_aboutnotepad.setMnemonic(KeyEvent.VK_A);
menu_aboutnotepad.addActionListener(AboutTheNotePad);
Menu_help.add(menu_aboutnotepad);
}//Menu_Help

public static void Open(String path,JLinePrint lineprint){//用于 拖拽文件进入窗口时候读取文件
File file = new File(path);
try {
FileReader in = new FileReader(file);
BufferedReader in_ = new BufferedReader(in);
String s = in_.readLine();
String temp = s;
s=in_.readLine();
if (file.canRead()) {
while (s != null) {
temp +=("\r\n"+s);                //存在一个String里面,到时候一次性赋给JTextArea
s = in_.readLine();                  //一行一行读取
}//while
JLinePrint.editText.setText(temp);
in_.close();
//读入即时存档文件
for(int i=0;++i<11;){
File file1=new File(path.replace(".txt", "")+String.valueOf(i)+".txt");//文件路径+文件名(不带.txt)+存档编号+.txt
if(file1.exists()){
in = new FileReader(file1);
in_ = new BufferedReader(in);
s = in_.readLine();//第一行读取时间
Notepad.Save_subMenu[i-1].setText(s);//给即时存档子菜单改变时间;保存文件名在后面加1-10,数组下标由0到9
Notepad.Load_subMenu[i-1].setText(s);//给即时读档子菜单改变时间
s=in_.readLine();//第二行开始读取正文
temp = "";
if (file1.canRead()) {
while (s != null) {
temp += (s + "\r\n");
s = in_.readLine();
}//while
Notepad.Save[i-1].s=temp;
Notepad.Load[i-1].s=Notepad.Save[i-1];
in_.close();
}//if
}//if
else{//如果没有该编号的存档
Notepad.Save_subMenu[i-1].setText("--------/--------     ");//给即时存档子菜单改变时间;
Notepad.Load_subMenu[i-1].setText("--------/--------     ");//给即时读档子菜单改变时间;
Notepad.Save[i-1].s="";
Notepad.Load[i-1].s=Notepad.Save[i-1];
}//else
}//for
lineprint.repaint_1();
final JFrame frame = new JFrame("读入成功!");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(null);
frame.setBounds(300, 400, 250, 125);
frame.setVisible(true);
JButton button = new JButton("确定");
button.setBounds(75, 50, 100, 30);
frame.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}//actionPerformed
});//addActionListener
// (String) File.getParent()返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。
//(File) File.getParentFile()返回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录,则返回 null。
SaveF.fileName=file.getName();
SaveF.filepath=file.getParent();
SaveF.path=file.getPath();
SaveF.FirstSave=true;//打开的时候算作有第一次保存,CTRL+S无需弹框保存
NewC.path1="";//新建恢复
}//if
}//try
catch (IOException e) {}//catch
}//Open

//转载自http://www.xuebuyuan.com/1168699.html
//将读入文件的函数加到了这里面
public static void JFrame_DragAndDrop(JMenuBar menubar, JFrame frame, final JLinePrint lineprint){//添加文件拖拽至窗口打开文件的事件
DropTargetAdapter DTA=new DropTargetAdapter(){
public void drop(DropTargetDropEvent DTDE){
try{
Transferable TF=DTDE.getTransferable();
if(TF.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){
DTDE.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
List<File> JL=(List<File>) TF.getTransferData(DataFlavor.javaFileListFlavor);
Iterator<File> iterator=JL.iterator();//如果没有import java.util.List;和import java.util.Iterator;的话无法使用 List的iterator()方法在接口里
while(iterator.hasNext()){
File f=iterator.next();
Open(f.getAbsolutePath(),lineprint);
}
DTDE.dropComplete(true);
}//if
else{
DTDE.rejectDrop();
}//else
}//try
catch(Exception e){}
}//drop
};//new DropTargetAdapter
new DropTarget(JLinePrint.editText,DnDConstants.ACTION_COPY_OR_MOVE,DTA);
}//JFrame_DragAndDrop()

private static void createAmdShowGui() {//Create
// 窗体
JFrame frame = new JFrame("无浪的记事本");
//	frame.setLayout(new FlowLayout());
frame.setSize(741, 565);
frame.setLocation(250, 100);
frame.setVisible(true);
frame.setResizable(true);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 菜单栏
JMenuBar menubar = new JMenuBar();
//	menubar.setSize(741, 23);
frame.add(menubar,BorderLayout.NORTH);
final JLinePrint lineprint=new JLinePrint();//建立(行框+文本框)的组件
//用于避免"文件"菜单项被遮住
JMenu menu=new JMenu("Line");
menu.setEnabled(false);
menubar.add(menu);
lineprint.setmenu(menu);//传参让menu随行框的变宽而变宽
Textfieldincident ActioneditText=new Textfieldincident(lineprint,menu);
JLinePrint.editText.addKeyListener(ActioneditText);
frame.add(lineprint,BorderLayout.WEST);
frame.add(lineprint.RollPane,BorderLayout.CENTER);
JLinePrint.editText.setFont(new Font("新宋体",Font.PLAIN,15));//设置文本框字体大小
lineprint.setFont(new Font("新宋体",Font.BOLD,15));//设置行框字体大小
lineprint.setForeground(Color.gray);//设置行框字体颜色

// 菜单:文件
Menu_File(menubar, frame,lineprint);
// 菜单:编辑
Menu_Edit(menubar);
// 菜单:格式
Menu_format(menubar);
// 菜单:查看
Menu_examine(menubar,lineprint,menu,frame);
// 菜单:帮助
Menu_Help(menubar);
//给窗口添加拖拽文件事件
JFrame_DragAndDrop(menubar, frame,lineprint);

}// createAndShowGui

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAmdShowGui();
}
});
}// main
}//notepad


帮助文档(这一行不要复制,从下一行开始复制)

请把该txt文件命名为帮助文档后放在D:\目录下面

记事本

这个帮助文档记录了在该记事本中用到的一些Java函数,以及类的实现思路,以及一些自己实现的算法

对这些Java函数将会列出它们在API的解释

如果较简单则直接给出函数用途

请注意:函数重复不会再次列出

End

新建类

所用函数:

JLabel . setFont(Font);

用于设置标签的字体

new Font(String int ,int);

Font的构造函数:

String能填入的是系统里的字体名称。

第一个int 填入的有以下四个

Font.PLAIN 常规
0

Font.BOLD 粗体
1

Font.ITAIC 斜体
2

Font.BOLD+FONT.ITAIC 粗斜体3

第二个int填入的是字体的大小,自己选值

Component.setBounds(int,int,int,int)

Component是像JTextArea,JTextField,JScrollPane,JTree这样的组件

前两个int是组件左上角的顶点在屏幕的位置

后两个int是组件的大小,前x轴后y轴

电脑屏幕的坐标系如下图所示

┌────────────→ x





│ Graphics









y

JFrame. add(Component)

给窗口添加组件

Component.addXXXListener(new XXXListener())

组件获得事件监听事件

public void actionPerformed(ActionEvent e)

组件执行动作的时候执行以下语句

Component.setMnemonic(KeyEvent.XXX)

给组件添加记忆符

JFrame.setResizable(boolean)

窗口能否改变大小

算法:

首先新建类、打开类、保存类,另存为类,退出类基本都是一起实现的

,它们都需要用到文件输出流和文件输入流的功能。所以相同的函数代码

就只在其中一个类里说了。

首先介绍新建类。Window记事本的新建功能:如果文本有改动就弹框

提示询问要不要保存,要就保存清空文本然后新建一个txt文件,不要就

清空文本并新建一个新的txt文件..

其次是filedialog本身具有询问文件名相同是否替换文件的对话框,但是

我修改成名字的输入不需要.txt后缀了,所以要自己编写一个。

文件输出流的调用用了个boolean来控制,只有前面的条件都实现后才

能领choose=true来调用输出流。

除此以外还会出现不保存按取消的时候会保存一个null.txt或nullnull.txt

,也需要用判断来排除掉这些意外状况。

总之就是原先代码就几行,意外状况越多代码就越改越厚了。

End

打开类

String regex="[.txt]";

正则表达式,用于在String里面除去.txt后缀名

new FileDialog(JFrame,String,int); 文件对话框

JFrame FileDialog关闭后所显示的窗口

String FileDialog的标题

String int 有以下两个常用项

FileDialog.Save 获得保存功能

FielDialog.Load 获得打开功能

String1.replaceAll(String2,String3)

将String1里的所有String2换成String3

new FileReader(String); String是指文件路径

用来读取字符文件的便捷类。

此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。

要自己指定这些值,

可以先在 FileInputStream 上构造一个 InputStreamReader。

new BufferedReader(FileReader);

缓冲读入流。使用这个类的原因是能用它的readLine()函数。

文本区域 串
缓冲阅读 文件阅读
文件

JTextArea StringBufferedReaderFileReaderFile

String

String

Line1,Line2,Line3……

(以\n为分隔符)

Stirng+=BufferedRead.readLine()

setText(String)

File.exit()

文件是否存在

JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

设置关掉时候消失

算法:

新建类,打开类,保存类,另存为类,退出类的结构基本都一样,

不一样的是本身所要实现的一些步骤不同。

打开需要让保存类不再执行弹出对话框的功能,而是Ctrl+S

直接保存,所以需要在打开的时候保存文件的地址然后赋给保存类

的path。这个不弹框直接保存的功能已经在保存类里实现了。

End

保存类

比如我打开一个文件路径为 D:\Backup\桌面\aaa.txt 的文件

Filediaglog.getDirectory(); D:\Backup\桌面\

Filedialog.getFile(); aaa.txt

File.getName() aaa

File.canRead()

文件可读

new BufferedWriter(FileWriter(File))

缓冲写入流

BufferedWriter.newLine()换行

算法:

保存类的特点:

①。首先对话框只弹出一次,保存成功后不再弹框。

②。新建和打开的时候保存的路径需要改变,前者变空,

继续弹框;后者记录打开文件的路径,不弹框。

弹不弹框我是用了一个if(!path.equals(""))来判断的。这样只要把

path置为""就会再次弹框。用了FirstSave是用来控制文件重名的情况,

其实忘了为什么要用FirstSave了, 这是刚开始就实现了的类。

另存为与该类放在了一起,与保存类不同的是,另存为类永远都要

弹框。所以比保存容易些。

End

页面设置类

JLabel.setForeground(Color.XXX)

给标签设置字体颜色

JLabel.setFont(new Font(String,int,int))

给标签设置字体

JPanel

JPanel 是一般轻量级容器。用于把几个组件连接在一起

void JPanel.setBorder(Border)

边框工厂

(CompoundBorder)BorderFactory.createCompoundBorder(Border ,Border )

创建一个合成边框,指定了用于外部和内部边缘的 border 对象。

BorderFactory.createTitledBorder(String)

给边框加个标题String

BorderFactory.createEmptyBorder()

产生一个空边框

算法;

这个类是在实现打印后加上的,也没什么算法,就是控制打印的排版而已。

End

打印类

PrinterJob

PrinterJob 类是控制打印的主要类。应用程序调用此类中的方法设置作业、(可选地)调用与用户的打印对话框,然后打印作业的页面。

PrinterJob.setPrintable(Printable)

这里的Printerable需要自己实现,自己编写打印的排版

(boolean)PrinterJob.printDialog()

显示打印对话框,返回true或false

PrinterJob.getCopies()获得打印的份数

Printjob.print();调用Printable接口里的

print(Graphics gra, PageFormat pf, int pageIndex) throws PrinterException方法

End

Print类

implements Printable

这个类编写来用于控制打印的排版

print(Graphics gra, PageFormat pf, int pageIndex)方法

PageFormat 类描述要打印的页面大小和方向。

算法:

①首先需要把(Graphics)gra转成(Graphics2D)g2 。

Graphics 类是所有图形上下文的抽象基类,允许应用程序在组件(已经在各种设备上实现)以及闭屏图像上进行绘制。

Graphics2D 类扩展 Graphics 类,以提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制。它是用于在 Java(tm) 平台上呈现二维形状、文本和图像的基础类。

②g2.setColor(Color);设置打印的颜色

g2.setFont(Font);设置打印的字体

Font.getSize2D;获得字体的高度

③g2.drawString(String,float,float);

在纸上画String字符串,左上角顶点为(float,float);

注意!!需要drawString两次才能在纸上出现字,第一次喷电子,第二次喷墨

④虽然drawString要两次,但是代码只需一行。

return Page_exit函数会再执行一次

return NO_SUCH_PAGE;函数不再执行。

需要注意的是如果你要打印的页数有五页,那么pageIndex的值为

0 0
1 1 223344

所以drawString可以很顺利地打印同一页两次,也就只需要一行代码了。

这里说一下我的实现方法:

我在打印类里面将文本区域内的文字根据\n字符分割成一个String字符

然后控制一页里drawString()的行数

这样会造成最后一页可能不满设定的行数,所以独立出来单独打印。

于是习惯性地把LeaveLine在执行一次语句后就直接设为0来终结打印

结果最后一页一直打印不出来

最后System.out.println(pageIndex)的时候发现同个数字出现两次,大致

推出来了。

于是加了个boolean来控制最后一页的两次drawString();

当时上网找了半天感觉这个最靠谱,可惜当时这段代码一点都看不懂,然后

把代码抄下来上概率论的时候一节课都在推这个代码了,那天是星期四然后又

用了星期五的时间,最后是星期六一整天都在研究怎么换页,一直到晚上才解

决了换页排版的问题.......

字体更换后的排版会有缺页缺行的现象,所以这个打印类只实现了颜色的

改变,字体样式,形状和大小只使用“新宋体”,“常规”和9,而不使用字体框内

设置的字体。

打印如果一行字数太多的话会超出纸。

End

Jtext类

用于加密解密类中的ObjectInputStream和ObjectOutputStream

这两个是直接保存对象的一个输出流

算法:

没什么算法,为加密解密类服务的。密文需要设为private然后用函数返回。

End

加密解密类

算法:

//加密解码的方式参照了http://blog.csdn.net/zhuxueke_830111/article/details/2009916的记事本例子

//该例子解密加密的字符默认为'a'和's'

//解密加密方式为 char^char 会变成一个奇怪的字符 即我们看到的密文 再一次 char^char 会恢复成原文

//这个类将每一个密码字符都用于解密加密,且不保存密码,打开时如果密码输入错误会导致解密失败,密文会变成另一段乱码,但是不影响已保存文件的内容

//本例子将JTextField用作密码框,限制输入字符数为10,并使显示字符为 '*' ;

//注意:密文无法使用BufferedWriter类进行保存,需要用ObjectInputStream类进行保存,否则解密的时候会多出字符

StringBuffer字符修改类,书上有,不解

在暑假的时候有看过记事本的例子,可惜当时那个例子是放在一个类里面

的所有的ActionListenrer都放在了一个actionPerformed(ActionEvent e)里面

,用的if-else-if-else实现功能读取,没怎么看懂,而且可读性也不太好,突然

就一大堆addActionListener(this)出来,然后各种数据一堆下来。可移植性也

不太好。如果用类来编写ActionListner的话以后有哪个软件需要同样的功能把

类直接移植过去稍微修改一下错误和一些变量名字就行了。

多类实现的方法的缺点就是会生成一大堆的clss文件。而且大部分功能的图形

界面定义都在构造函数,然后在actionPerformed(ActionEvent e)里setVisible,

所以会造成在打开记事本的时候有一点卡顿现象。

End

退出类

退出的时候提示保存。

算法:

跟新建差不多,需要弹框提示保存,然后退出窗口。

End

撤销类

定义了两个栈

一个栈放在文本框事件类里面用于撤销

另一个栈放在撤销类里面用于恢复

可以直接撤销到极限或恢复到极限。

End

恢复类

与撤销类和文本框事件类是兄弟类。

End

JLinePrint类

//转载自http://zhidao.baidu.com/link?url=_LX5dnt3qCyQgCyLHN4nT7GyXpKpBdRWqCOyX4kzpgikEAcWHGK3MdkTeLRSKCSzMYzmUNYRR81KqxT09bpPwK

//创建一个输出文本行号附带文本框编辑的组件

//加以改动,将repaint方法放在文本框的键盘事件以及打开事件里执行。添加自己的注释。

//增添了鼠标滑轮事件和拖拽滚动条事件,行框在行数超过1000时改变大小

editText.addCaretListener(new CaretListener(){

public void caretUpdate(CaretEvent arg0){}}

这个监听事件可以在文本框或文本区域有任何改变其文本的行为的时候

调用该函数

(int)JTextArea.getCaretPosition()获得光标位置

这里说一下,JTextArea其实就是一个String,它的换行行为都是通过\n实现的

而获得的光标位置就是这个字符在这个String里的位置,那么通过这个数字和上一个

\n的距离和前面\n的数量就可以得到该位置的行数和列数

JTextArea.getLineOfOffset(JTextArea.getCaretPosition())

将文本中的偏移量转换为行号。返回值范围为0-Line-1;

JTextArea.getLineStartOffset(Line-1)

确定给定行起始处的偏移量。

即给定行之前有多少个字符

然后用光标所在位置前有多少个字符

减去这个数值再加1即为当前的列数

Panel.setMinimumSize(Dimension(int,int))

将组件的最小大小设置为常量值。对 getMinimumSize 的后续调用总是返回此值。将最小大小设置为 null 可还原默认的行为。

paint(Graphics g)方法在一个组件上使用Graphics类作画,

用repaint()方法可以把组件上的画清空然后重新作画,

即刷新作画使其发生改变。

JScrollPane.addMouseWheelListener(new MouseWheelListener()

public void mouseWheelMoved(MouseWheelEvent)

鼠标滑轮事件

用于在滑轮的时候刷新行框

Thread.sleep(int);暂停指定毫秒数

Component.setPreferredSize(new Dimension(30+x,25));

改变组件大小

JTextArea.viewToModel(Point); 给定的视图坐标系换到最近的模型的位置。 即提供当前视图中的文本位置

(JViewPoint)JScollPane.getViewPort() 返回滚动视窗

(Point)JViewPoint.getViewPosition(); 返回视图坐标,若无视图返回(0,0);

start=editText.viewToModel(RollPane.getViewport().getViewPosition());

start获取的是不在文本框当前视图的滚动条上面的字符个数(包括换行键,换行键算一个字符)

Document doc=editText.getDocument();//获取editText的Document类

AbstactDocument.返回视图依赖的根元素().(java.swing.text.Element)返回子元素指数接近给定的偏移量(int)+1

startline获取的是当前视图下文本框的第一行是几行

int startline=doc.getDefaultRootElement().getElementIndex(start)+1;

endline获取的是当前视图下文本框的最后一行是几行

int endline=doc.getDefaultRootElement().getElementIndex(end)+1;

(Graphics.getFontMetrics(JTextField.getFont())).getHeight()

获取文本框内字体的高度,用于让行数对应文本框内的文字

int fontHeight=(g.getFontMetrics (editText.getFont()).getHeight());

(Graphics.得到当前字体的字体度量(文本框里的字体)).获得字体的大小

fontDesc用于校准第一行的1与边框顶端的偏移量

int fontDesc=(g.getFontMetrics(editText.getFont())).getDescent();

算法:

完成记事本后又给这个类增加了文本区域拖拽字符串令其移动的功能。

这个类用到的最重要的函数是

JTextArea.viewToModel(Point);

给定的视图坐标系换到最近的模型的位置。 即提供当前视图中的文本位置

我的定义是:

给出当前坐标点之前文本的字符数。

知道这个数字可以知道这个点在文本框的坐标位置,从而实现字符串拖拽功能,

这是Window记事本不存在的功能,但是在Word文档,EClipse里都能存在,但是拖拽时候鼠标指针不能变成虚线,而且选中的文本取消了选中,可能还没找到方法吧。

End

即时读档类

即时读档比即使存档轻松,就是把存储好的String放入文本区域就行了。

灵感来源于以前玩的GBA模拟器。

End

即时存档类

即时存档除了保存当前文本区域的字符串于一个String中以外还要保存一个

txt文件在原文件目录下,所以要在已存txt文件下才能使用即时存档

<html><ul><font face=新宋体 font size=4><i>请保存文件后再使用即时存读档功能。</i></font></ul></html>

在JLabel使用的html格式的输出

JLabel Web程序语言控制

End

时间日期类

Date类

建立SimpleDataFormate("yyyy'年'MM月dd日HH时mm分ss秒(a)(EE)");

用SimpleDataFormate.format(Date)来确定Date类的输出格式;

End

转到类

Integer.parseInt(String)将String转成数字,当然如果String里有非数字是不能转的。

String.matches(正则表达式);

String1.split(String2);根据String2来分割String1

JTextArea.setSelectionStart(int1);

JTextArea.setSelectionEnd(int2);

int1不等于int2的时候会选中JTextArea 第int1列和第int2列之间的字符串。

相同时光标会移到该位置

例如

0 起 1 点 2 终 3 点 4 都 5 一 6 样 7 即 8 一 9 个 10 光 11 标 12

JTextArea.setSelectionStart(0);

JTextArea.setSelectionEnd(1);

选中"起"

JTextArea.setSelectionStart(3);

JTextArea.setSelectionEnd(9);

选中"点都一样即一"

JTextArea.setSelectionStart(9);

JTextArea.setSelectionEnd(9);

光标在9的位置

JFrame.setResizable(boolean)设定窗口是否可改变大小

End

剪切类

String.substring(int,int)

获得指定位置的子串。

0 起 1 点 2 终 3 点 4 都 5 一 6 样 7 即 8 一 9 个 10 光 11 标 12

String.substring(0,1)="起"

String.substring(3,9)="点都一样即一";

String.substring(1,1)="";

End

复制类

需要注意的是复制的内容可以重复粘贴,但是剪切的内容只能粘贴一次

所以需要用一个boolean来判断是复制还是剪切,从而决定是否用清空

String。

End

粘贴类

String1.replaceRange(String2,int3,int4)

用String2替换String1在int3和int4之间的字符串。

End

删除类

用String1.replaceRange(String2,int3,int4)

只是把String2改成""即可;

End

查找和替换类

主要函数:

JTextArea.setSelectionStart(int1);

JTextArea.setSelectionEnd(int2);

String1.replaceRange(String2,int3,int4);

主要算法:正向KMP算法,用于向下查找

逆向KMP算法,用于向上查找

向上查找容易点,因为它查找的过程中坐标直接指向最后一个

向下查找查找的时候光标还是指向最后一个,所以需要把光标位置往前

提才能进行持续性查找。

下面这段代码用于不区分大小写的查找。

String str3="("+str1.toLowerCase()+"|"+str1.toUpperCase()+")";

return str.matches(str3);

注意这里的String都是只有一个字符的。

不同于C,Java的String获得指定位置的字符的时候要用

String.charAt(int);

String.valueOf(XXX),可以将XXX转成String类型,例如

String str1=String.valueOf(p.charAt(j));

String1.replaceAll(String2,String3)

把String1里的String2都替换成String3。

End

全选类

JTextArea.editText.selectAll();

选择全部

End

字体类

GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); // 返回系统所有可用字体

GraphicsEnvironment 类描述了 Java(tm) 应用程序在特定平台上可用的 GraphicsDevice 对象和 Font 对象的集合。

GraphicsEnvironment.getLocalGraphicsEnvironment()

返回本地 GraphicsEnvironment。

GraphicsEnvironment.getAvailableFontFamilyNames();

返回一个包含此 GraphicsEnvironment 中所有字体系列名称的数组,它针对默认语言环境进行了本地化。

JList..setSelectedValue(String, true);

默认选择列表中的String。

JList.addListSelectionListener(new ListSelectionListener(){

public void valueChanged(ListSelectionEvent e) {

JList的监听事件

End

字体颜色类

Color = JColorChooser.showDialog(JFrame, String, Color);

弹出颜色选择框。

JTextArea.setForeground(Color)

设置字体颜色

End

背景颜色类

JTextArea.setBackground(BackGroundColor);

End

文本框事件类

implements KeyListener

public void keyPressed(KeyEvent e)

键被按下的时候

public void keyReleased(KeyEvent e1)

键弹起的时候

public void keyTyped(KeyEvent e2)

键按下或弹起的时候

功能:

这个类用来监听文本框的按键。

用于在按键的时候适时改变行框的大小。

以及把文本入栈来等待撤销。

还有控制状态栏的文本改变。

End

文本框鼠标事件类

implements MouseListener

这个类后来跟JLinePrint类合并了

public void mouseClicked(MouseEvent e)

鼠标点击的时候

public void mouseEntered(MouseEvent arg0)

鼠标进入

public void mouseExited(MouseEvent arg0)

鼠标出去

public void mouseExited(MouseEvent arg0)

鼠标出去

public void mousePressed(MouseEvent arg0)

鼠标按下(包括左键右键和滑轮按下)

左键按下为16,滑轮按下为8,右键按下为4

public void mouseReleased(MouseEvent arg0)

鼠标弹起

算法:

用这几个函数实现了字符串的拖拽功能

mouseDragged//鼠标拖拽

if(e.getModifiers()==16){//如果拖动时候使用的是左键

if(isChoosesubstring){

Mousepos=editText.viewToModel(e.getPoint());

editText.setSelectionStart(Mousepos);

editText.setSelectionEnd(Mousepos);

}//if

}//if

}//if

mouseMoved //鼠标移动

Mousepos=editText.viewToModel(e.getPoint());

mousePressed//鼠标按下

if(e.getModifiers()==16){//左键按下

if(isChoosesubstring){//如果已经选中了一段文本

if(Mousepos>Start && Mousepos<End){//如果鼠标时按下选中的文本上的

isClickedsubstring=true;//那么 “点在文本上” 这个boolean变为true

}//if

else{

isChoosesubstring=false; //否则,"选中文本" 这个boolean变为false

Start=0; //选中文本的始下标变为0

End=0; //选中文本的尾下标变为0

}//else

}//if

}//if

mouseReleased//鼠标弹起

if(e.getModifiers()==16){ //左键弹起

//以下两行代码只要弹起左键随时都会执行。

int Start=editText.getSelectionStart(); //获得选中文本的始下标

int End=editText.getSelectionEnd(); //获得选中文本的尾下标

if(Start!=End){

isChoosesubstring=true;

s=editText.getText().substring(Start,End);

this.Start=Start;

this.End=End;

}//if

else if(isClickedsubstring){

if(isClickedsubstring){

editText.replaceRange("", this.Start, this.End);

Mousepos=editText.viewToModel(e.getPoint());

editText.insert(s, Mousepos);

isClickedsubstring=false;

this.Start=0;

this.End=0;

}//if

}//else

}//if

End

关于记事本类

implements ActionListener

By @author wuwave

所用时间:

2014.11.4-2014.11.18

End

帮助主题类

JTree 树组件

JTree.getSelectionModel();

返回选择的模型。

TreeSelectionModel.setSelectionMode()

设置选择模型,它必须是 SINGLE_TREE_SELECTION、CONTIGUOUS_TREE_SELECTION 或 DISCONTIGUOUS_TREE_SELECTION 之一。

SINGLE_TREE_SELECTION 一次只能选择一个路径。

CONTIGUOUS_TREE_SELECTION 选择只能是连续的。仅当提供 RowMapper 实例时,这才被强制执行。即:如果不设置任何 RowMapper,它的功能与 DISCONTIGUOUS_TREE_SELECTION 相同。

DISCONTIGUOUS_TREE_SELECTION 选择可以包含任何数量的项,这些项不必是连续的。

DefaultMutableTreeNode类 是树数据结构中的通用节点。

End

Notepad类

JMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_MASK));

设置快捷键CTRL+P

拖拽文件进入窗口读取文件事件

DropTargetAdapter类

接收放置目标事件的抽象适配器类。

DropTargetAdapter DTA=new DropTargetAdapter(){

public void drop(DropTargetDropEvent DTDE){

Transferable TF=DropTargetDropEvent.getTransferable();

此方法返回与 drop 相关的 Transferable 对象。

Transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)

用于判断Java是否支持拖拽的文件

javaFileListFlavor

要将文件列表传入 Java(及底层平台)或从中传出,需要使用此类型/子类型的 DataFlavor 和 java.util.List 的表示形式类。

DropTargetDropEvent.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

允许接受拖拽文件的移动和复制。

List JL=(List)TF.getTransferData(DataFlavor.javaFileListFlavor);

获得文件的列表

import java.util.List;

import java.util.Iterator;

Iterator iterator=JL.iterator();

获得文件列表的迭代器

Iterator.hasNext()

有后文,即直接拖动了多个文件进去,不过因为我编的打开函数

是直接覆盖的,所以只显示其中一个。

File f=(File)iterator.next();

Open(f.getAbsolutePath(),lineprint);

获得下一个文件,放入打开函数里执行

new DropTarget(JLinePrint.editText,DnDConstants.ACTION_COPY_OR_MOVE,DTA);

把拖拽事件放入组件,这里我放入的是文本区域。没有这句话拖拽事件无法工作。

End
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: