[JAVA] 一个可以编辑、编译、运行Java简单文件的记事本java实现

本来是Java课做一个仿windows记事本的实验,后来突然脑子一热,结果就给它加了一个编译运行Java文件的功能。

本工程总共大约3000行代码,基本上把所学的java界面、文件、控件的功能都包含在内啦。除此之外俺还脑子一热给这个文本编辑器加了个可以编译运行java文件的功能,但是由于多线程还不咋滴,所以有些需要在DOS输入的java文件就无法运行啦。

现在过了一个寒假,好像有点忘了,所以拿出来研究一下,顺便写个博客,全做复习一下java啦,嘻嘻>_<!

 notepad包:

1、关于对话框 :介绍软件运行环境作者,版权声明。这里用JDialog便于生成模式窗口,用2个JButton一个是OK按钮,一个是无边框图标,用4个Jlable来显示文字(这里涉及字体颜色,字体设置)。更多介绍请看代码:(可单独运行)

 1 package notepad;
 2 //about 对话框
 3 import java.awt.Color;
 4 import java.awt.Font;
 5 import java.awt.event.ActionEvent;
 6 import java.awt.event.ActionListener;
 7 import javax.swing.ImageIcon;
 8 import javax.swing.JButton;
 9 import javax.swing.JDialog;
10 import javax.swing.JFrame;
11 import javax.swing.JLabel;
12 import javax.swing.JPanel;
13 
14 public class AboutDialog implements ActionListener{
15     public JDialog Dialog;
16     public JButton OK,Icon;
17     public JLabel Name,Version,Author,Java;
18     public JPanel Panel;
19     AboutDialog(JFrame notepad, int x, int y) {//构造函数(父窗口,x,y)
20         //实例化界面控件
21         Dialog=new JDialog(notepad,"About Notepad...",true);//用JDialog便于写出模式窗口
22         OK=new JButton("OK");
23         Icon=new JButton(new ImageIcon("50.png"));
24         Name=new JLabel("Notepad");
25         Version=new JLabel("Version 1.0");
26         Java=new JLabel("JRE Version 6.0");
27         Author=new JLabel("Copyright (c) 2013-11-30 TaoLi. No rights reserved.");
28         Panel=new JPanel();//用一个JPanel使界面显得更美观
29         Color c=new Color(0,95,191);//颜色构造函数(r,g,b)
30         //美化界面控件
31         Name.setForeground(c);//字体前景颜色
32         Version.setForeground(c);
33         Java.setForeground(c);
34         Panel.setBackground(Color.WHITE);//Panel设为白色
35         OK.setFocusable(false);
36         Dialog.setSize(280, 180);//控件设置大小
37         Dialog.setLocation(x, y);//控件设置位置
38         Dialog.setResizable(false);//大小不可变
39         Dialog.setLayout(null);
40         Panel.setLayout(null);
41         OK.addActionListener(this);//给按钮加入监听
42         Icon.setFocusable(false);
43         Icon.setBorderPainted(false);//无边框处理
44         Author.setFont(new Font(null,Font.PLAIN,11));//设置字体
45         //组合各个控件并设置各自大小
46         Panel.add(Icon);//加入托盘
47         Panel.add(Name);
48         Panel.add(Version);
49         Panel.add(Author);
50         Panel.add(Java);
51         Dialog.add(Panel);//加入主界面
52         Dialog.add(OK);
53         Panel.setBounds(0, 0, 280, 100);//Panel大小设置
54         OK.setBounds(180, 114, 72, 26);//OK大小设置
55         Name.setBounds(80, 10, 160, 20);
56         Version.setBounds(80, 27, 160, 20);
57         Author.setBounds(15, 70, 250, 20);
58         Java.setBounds(80, 44, 160, 20);
59         Icon.setBounds(16, 14, 48, 48);
60     }
61     public void actionPerformed(ActionEvent e) {//事件监听
62         Dialog.setVisible(false);
63         Dialog.dispose();
64     }
65     public static void main(String args[]){//测试用的main函数
66         JFrame f=new JFrame();
67         AboutDialog a=new AboutDialog(f,400,400);
68         a.Dialog.setVisible(true);
69     }
70 }
AboutDialog.java

2、颜色选择对话框: 主要为主窗口的文字的前景和背景颜色设置,主窗口的背景和选中时的背景颜色设置;其中第二个窗口负责选择颜色(也可直接输入RGB值)。这里窗口1上半部分主要由4个JLable用于文字显示,4个JButton用于分别功能选择,2个JTextArea用于显示效果;窗口2用了2维的按钮矩阵[16][16]来显示颜色。这里设置好的颜色值分别保存在public Color NFC,NBC,SFC,SBC;//4个颜色中,当其他函数调用时可以通过访问这些值来做相关操作;此外这里还把选择的数据保存在文件里了,刚开始初始化和数据改变都涉及文件操作。更多介绍请看代码:(可单独运行)

   

  1 package notepad;
  2 //2个窗口,2个类
  3 import java.awt.Color;
  4 import java.awt.Component;
  5 import java.awt.Font;
  6 import java.awt.GridLayout;
  7 import java.awt.event.ActionEvent;
  8 import java.awt.event.ActionListener;
  9 import java.awt.event.KeyEvent;
 10 import java.awt.event.KeyListener;
 11 import java.awt.event.WindowEvent;
 12 import java.awt.event.WindowListener;
 13 import java.io.RandomAccessFile;
 14 
 15 import javax.swing.JButton;
 16 import javax.swing.JDialog;
 17 import javax.swing.JFrame;
 18 import javax.swing.JLabel;
 19 import javax.swing.JPanel;
 20 import javax.swing.JTextArea;
 21 import javax.swing.JTextField;
 22 
 23 public class ColorDialog implements ActionListener, WindowListener{
 24     public JDialog Dialog;
 25     public JLabel NFL,NBL,SFL,SBL;//4个label
 26     public JTextArea Normal,Selected;//2个文本显示
 27     public JButton NFB,NBB,SFB,SBB,OK,Cancel,Reset;//7个按钮
 28     public Color NFC,NBC,SFC,SBC;//4个颜色
 29     public ColorChooser Chooser;//1个颜色选择自定义类实例
 30     private RandomAccessFile file;//存储颜色文件
 31     public ColorDialog(JFrame notepad, int x, int y){//构造函数(父类,x,y)
 32         try {//初始化信息,从保存文件读取
 33             file=new RandomAccessFile("D:\\colorData.txt","rw");
 34             if(file.length()!=0){
 35                 NFC=new Color(file.readInt(),file.readInt(),file.readInt());//初始化四种颜色
 36                 NBC=new Color(file.readInt(),file.readInt(),file.readInt());
 37                 SFC=new Color(file.readInt(),file.readInt(),file.readInt());
 38                 SBC=new Color(file.readInt(),file.readInt(),file.readInt());
 39             }else{
 40                 NFC=new Color(0,0,0);//初始化四种颜色
 41                 NBC=new Color(249,249,251);
 42                 SFC=new Color(0,0,0);
 43                 SBC=new Color(191,207,223);
 44             }
 45             if(file!=null)file.close();
 46         } catch (Exception e) {
 47             e.printStackTrace();
 48         } 
 49         //实例化组建
 50         Dialog=new JDialog(notepad,"Color...",true);
 51         NFL=new JLabel("Normal Foreground:");//初始化四个jlable
 52         NBL=new JLabel("Normal Background:");
 53         SFL=new JLabel("Selected Foreground:");
 54         SBL=new JLabel("Selected Background:");
 55         Normal=new JTextArea("\n    Normal    正常");//2个文本显示区
 56         Selected=new JTextArea("\n    Selected  选中 ");
 57         NFB=new JButton("");//四个颜色选择按钮
 58         NBB=new JButton("");
 59         SFB=new JButton("");
 60         SBB=new JButton("");
 61         OK=new JButton("OK");//3个逻辑按钮
 62         Cancel=new JButton("Cancel");
 63         Reset=new JButton("Reset");
 64         Chooser=new ColorChooser(Dialog, x+65, y-15);//一个颜色选择器
 65         //各个组件设置
 66         Normal.setEditable(false);//设置1文本显示区不可编辑
 67         Normal.setFocusable(false);
 68         Normal.setFont(new Font("新宋体", 0, 16));//初始化文本显示区
 69         Normal.setForeground(NFC);
 70         Normal.setBackground(NBC);
 71         Selected.setEditable(false);//设置2文本显示区不可编辑
 72         Selected.setFocusable(false);
 73         Selected.setFont(Normal.getFont());//初始化文本显示区
 74         Selected.setForeground(SFC);
 75         Selected.setBackground(SBC);
 76         NFB.setBackground(NFC);//设置4个颜色选择按钮颜色
 77         NBB.setBackground(NBC);
 78         SFB.setBackground(SFC);
 79         SBB.setBackground(SBC);
 80         Dialog.setLayout(null);
 81         Dialog.setLocation(x, y);
 82         Dialog.setSize(410, 220);
 83         Dialog.setResizable(false);
 84         Reset.setFocusable(false);
 85         OK.setFocusable(false);
 86         Cancel.setFocusable(false);
 87         //组建组合并设置位置大小
 88         Dialog.add(Normal);
 89         Dialog.add(Selected);
 90         Dialog.add(NFL);
 91         Dialog.add(NBL);
 92         Dialog.add(SFL);
 93         Dialog.add(SBL);
 94         Dialog.add(SBB);
 95         Dialog.add(SFB);
 96         Dialog.add(NBB);
 97         Dialog.add(NFB);
 98         Dialog.add(OK);
 99         Dialog.add(Cancel);
100         Dialog.add(Reset);
101         SBB.setBounds(144, 100, 60, 22);
102         SFB.setBounds(144, 70, 60, 22);
103         NBB.setBounds(144, 40, 60, 22);
104         NFB.setBounds(144, 10, 60, 22);
105         NFL.setBounds(10, 10, 130, 22);
106         NBL.setBounds(10, 40, 130, 22);
107         SFL.setBounds(10, 70, 130, 22);
108         SBL.setBounds(10, 100, 130, 22);
109         Normal.setBounds(220, 10, 174, 56);
110         Selected.setBounds(220, 66, 174, 56);
111         Reset.setBounds(10, 160, 74, 24);
112         OK.setBounds(236, 160, 74, 24);
113         Cancel.setBounds(320, 160, 74, 24);
114         Dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
115         Dialog.addWindowListener(this);//屏幕监听
116         //7个按钮监听
117         NFB.addActionListener(this);
118         NBB.addActionListener(this);
119         SFB.addActionListener(this);
120         SBB.addActionListener(this);
121         Reset.addActionListener(this);
122         OK.addActionListener(this);
123         Cancel.addActionListener(this);
124     }
125     public void setTextAreaColor(){//将textArea的颜色设置为4个按钮的背景颜色
126         Normal.setForeground(NFB.getBackground());
127         Normal.setBackground(NBB.getBackground());
128         Selected.setForeground(SFB.getBackground());
129         Selected.setBackground(SBB.getBackground());
130     }//(获取组件背景颜色和设置组件背景颜色)
131     public void cancel(){//cancel时调用的函数
132         Normal.setForeground(NFC);
133         Normal.setBackground(NBC);
134         Selected.setForeground(SFC);
135         Selected.setBackground(SBC);
136         NFB.setBackground(NFC);
137         NBB.setBackground(NBC);
138         SFB.setBackground(SFC);
139         SBB.setBackground(SBC);
140         Dialog.setVisible(false);
141     }
142     public void actionPerformed(ActionEvent e) {//事件监听函数(适合多事件的处理简洁方便)
143         Object obj=e.getSource();//通过资源比较的
144         if(obj==Reset){//恢复原来
145             NFB.setBackground(new Color(0,0,0));
146             NBB.setBackground(new Color(249,249,251));
147             SFB.setBackground(new Color(0,0,0));
148             SBB.setBackground(new Color(191,207,223));
149             setTextAreaColor();
150         }
151         else if(obj==OK){//更新
152             NFC=NFB.getBackground();
153             NBC=NBB.getBackground();
154             SFC=SFB.getBackground();
155             SBC=SBB.getBackground();
156             try {//数据写入文件
157                 file=new RandomAccessFile("D:\\colorData.txt","rw");
158                 file.writeInt(NFC.getRed());file.writeInt(NFC.getGreen());file.writeInt(NFC.getBlue());
159                 file.writeInt(NBC.getRed());file.writeInt(NBC.getGreen());file.writeInt(NBC.getBlue());
160                 file.writeInt(SFC.getRed());file.writeInt(SFC.getGreen());file.writeInt(SFC.getBlue());
161                 file.writeInt(SBC.getRed());file.writeInt(SBC.getGreen());file.writeInt(SBC.getBlue());
162                 if(file!=null)file.close();
163             } catch (Exception e1) {
164                 e1.printStackTrace();
165             }            
166             Dialog.setVisible(false);
167         }
168         else if(obj==Cancel)//取消
169             cancel();
170         else{//其他情况直接获取颜色并更新
171             Chooser.init(((Component) obj).getBackground());
172             Chooser.Dialog.setVisible(true);
173             ((Component) obj).setBackground(Chooser.New.getBackground());
174             setTextAreaColor();
175         }
176     }
177     public void windowClosing(WindowEvent e) {//重定义窗口关闭操作
178         cancel();
179     }//必须加Dialog.addWindowListener(this);屏幕监听,并且所有接口都要实现
180     public void windowActivated(WindowEvent arg0) {}
181     public void windowClosed(WindowEvent arg0) {}
182     public void windowDeactivated(WindowEvent arg0) {}
183     public void windowDeiconified(WindowEvent arg0) {}
184     public void windowIconified(WindowEvent arg0) {}
185     public void windowOpened(WindowEvent arg0) {}
186     
187     public static void main(String args[]){//main函数,测试用
188         JFrame c=new JFrame();
189         ColorDialog a=new ColorDialog(c,400,400);
190         a.Dialog.setVisible(true);        
191     }
192 }
193 
194 class ColorChooser implements ActionListener,WindowListener,KeyListener{
195     JDialog Dialog;
196     JButton Choice[][],Old,New,OK,Cancel;//结果保存在New的背景颜色中
197     JPanel Panel;
198     JTextField R,G,B;
199     JLabel OldLabel,NewLabel,RL,GL,BL;
200     ColorChooser(JDialog color,int x, int y){//构造函数(parent,x,y)
201         //实例化
202         Dialog=new JDialog(color,true);
203         Choice=new JButton[16][16];//颜色选择区按钮
204         Panel=new JPanel();
205         Old=new JButton("");
206         New=new JButton("");
207         OldLabel=new JLabel("Old:");
208         NewLabel=new JLabel("New:");
209         RL=new JLabel("R:");
210         GL=new JLabel("G:");
211         BL=new JLabel("B:");
212         R=new JTextField("");
213         G=new JTextField("");
214         B=new JTextField("");
215         OK=new JButton("OK");
216         Cancel=new JButton("Cancel");
217         //按钮的布局格式(表格布局)
218         Panel.setLayout(new GridLayout(16,16,0,0));//设置表格布局16x16.存放颜色选择按钮
219         int i=0,j=0;
220         Color c;
221         Choice[0 ][15]=new JButton("");Choice[0 ][15].setBackground(new Color(255,255,255));//设置按钮背景颜色
222         Choice[1 ][15]=new JButton("");Choice[1 ][15].setBackground(new Color(255,223,191));
223         Choice[2 ][15]=new JButton("");Choice[2 ][15].setBackground(new Color(255,207,207));
224         Choice[3 ][15]=new JButton("");Choice[3 ][15].setBackground(new Color(223,191,255));
225         Choice[4 ][15]=new JButton("");Choice[4 ][15].setBackground(new Color(207,207,255));
226         Choice[5 ][15]=new JButton("");Choice[5 ][15].setBackground(new Color(191,223,255));
227         Choice[6 ][15]=new JButton("");Choice[6 ][15].setBackground(new Color(207,255,207));
228         Choice[7 ][15]=new JButton("");Choice[7 ][15].setBackground(new Color(255,  0,  0));
229         Choice[8 ][15]=new JButton("");Choice[8 ][15].setBackground(new Color(  0,255,  0));
230         Choice[9 ][15]=new JButton("");Choice[9 ][15].setBackground(new Color(  0,  0,255));
231         Choice[10][15]=new JButton("");Choice[10][15].setBackground(new Color(255,255,  0));
232         Choice[11][15]=new JButton("");Choice[11][15].setBackground(new Color(  0,255,255));
233         Choice[12][15]=new JButton("");Choice[12][15].setBackground(new Color(255,  0,255));
234         Choice[13][15]=new JButton("");Choice[13][15].setBackground(new Color(255,255,223));
235         Choice[14][15]=new JButton("");Choice[14][15].setBackground(new Color(223,255,255));
236         Choice[15][15]=new JButton("");Choice[15][15].setBackground(new Color(255,223,255));
237         for(i=0;i<16;i++){
238             c=Choice[i][15].getBackground();//获取背景颜色
239             for(j=0;j<16;j++){
240                 if(j!=15){
241                     Choice[i][j]=new JButton("");
242                     Choice[i][j].setBackground(new Color(c.getRed()*(j+1)/16,c.getGreen()*(j+1)/16,c.getBlue()*(j+1)/16));
243                 }
244                 Choice[i][j].setFocusable(false);//
245                 Choice[i][j].addActionListener(this);
246                 Panel.add(Choice[i][j]);
247             }
248         }
249         //控件格式设置和监听
250         Dialog.setSize(280,250);
251         Dialog.setLayout(null);
252         Dialog.setLocation(x, y);
253         Dialog.setResizable(false);
254         Dialog.add(Panel);
255         Panel.setBounds(10, 10, 160, 160);
256         Dialog.add(Old);
257         Dialog.add(OldLabel);
258         Old.setEnabled(false);
259         Old.setBorderPainted(false);
260         Old.setBounds(214, 10, 44, 22);
261         OldLabel.setBounds(180, 10, 44, 22);
262         Dialog.add(New);
263         Dialog.add(NewLabel);
264         New.setEnabled(false);//不可按****
265         New.setBorderPainted(false);//无边界***
266         New.setBounds(214, 32, 44, 22);
267         NewLabel.setBounds(180, 32, 44, 22);
268         Dialog.add(R);
269         Dialog.add(G);
270         Dialog.add(B);
271         R.setBounds(214, 97, 44, 22);
272         G.setBounds(214, 123, 44, 22);
273         B.setBounds(214, 149, 44, 22);
274         Dialog.add(RL);
275         Dialog.add(GL);
276         Dialog.add(BL);
277         RL.setBounds(196, 97, 16, 22);
278         GL.setBounds(196, 123, 16, 22);
279         BL.setBounds(196, 149, 16, 22);
280         Dialog.add(OK);
281         Dialog.add(Cancel);
282         OK.setFocusable(false);
283         Cancel.setFocusable(false);
284         OK.setBounds(106, 190, 74, 24);
285         Cancel.setBounds(190, 190, 74, 24);
286         OK.addActionListener(this);
287         Cancel.addActionListener(this);
288         G.addKeyListener(this);
289         R.addKeyListener(this);
290         B.addKeyListener(this);
291     }
292     public void setText(Color c){//由颜色修改RGB的数值函数
293         R.setText(String.valueOf(c.getRed()));
294         G.setText(String.valueOf(c.getGreen()));
295         B.setText(String.valueOf(c.getBlue()));
296     }//(JTextField的文本设置)
297     public void init(Color c){//初始化颜色(new old 显示和RGB数值区)
298         New.setBackground(c);
299         Old.setBackground(c);
300         setText(c);
301     }
302     public void actionPerformed(ActionEvent e) {//总监听
303         Object obj=e.getSource();
304         if(obj==OK) Dialog.setVisible(false);
305         else if(obj==Cancel){//取消
306             New.setBackground(Old.getBackground());//设回原来值
307             Dialog.setVisible(false);
308         }
309         else{
310             New.setBackground(((Component) obj).getBackground());
311             setText(New.getBackground());
312         }
313     }
314     public void windowClosing(WindowEvent e) {//窗口关闭定义
315         New.setBackground(Old.getBackground());
316         Dialog.setVisible(false);
317     }
318     public void keyReleased(KeyEvent e) {//案件监听用于填写RGB数值并修改new显示
319         try{
320             int r,g,b;
321             if(R.getText().length()==0) r=0;
322             else r=Integer.valueOf(R.getText());
323             if(G.getText().length()==0) g=0;
324             else g=Integer.valueOf(G.getText());
325             if(B.getText().length()==0) b=0;
326             else b=Integer.valueOf(B.getText());
327             New.setBackground(new Color(r,g,b));
328         }
329         catch(NumberFormatException nfe){setText(New.getBackground());}//异常处理1
330         catch(IllegalArgumentException iae){setText(New.getBackground());}//2变回原来
331     }//(按键监听)
332     public void keyPressed(KeyEvent e) {}
333     public void keyTyped(KeyEvent e) {}
334     public void windowActivated(WindowEvent arg0) {}
335     public void windowClosed(WindowEvent arg0) {}
336     public void windowDeactivated(WindowEvent arg0) {}
337     public void windowDeiconified(WindowEvent arg0) {}
338     public void windowIconified(WindowEvent arg0) {}
339     public void windowOpened(WindowEvent arg0) {}
340 }
ColorDialog.java

 3、确认对话框: 主要是在一些关键的步骤让用户确认是否进行操作的对话框。其选择的结果保存在state里面,外部函数可以访问这个值来查看用户的选择。更多介绍请看代码:(可单独运行)

 1 package notepad;
 2 import java.awt.BorderLayout;
 3 import java.awt.Color;
 4 import java.awt.FlowLayout;
 5 import java.awt.Font;
 6 import java.awt.event.ActionEvent;
 7 import java.awt.event.ActionListener;
 8 import java.awt.event.WindowEvent;
 9 import java.awt.event.WindowListener;
10 import javax.swing.JButton;
11 import javax.swing.JDialog;
12 import javax.swing.JFrame;
13 import javax.swing.JLabel;
14 import javax.swing.JPanel;
15 
16 public class EnsureDialog implements WindowListener, ActionListener{
17     public int YES,NO,CANCEL,Status;
18     public JDialog Ensure;
19     public JButton Yes,No,Cancel;
20     public JLabel Question;
21     public JPanel ButtonPanel,TextPanel;
22     EnsureDialog(JFrame notepad, int x, int y) {
23         YES=0;
24         NO=1;
25         CANCEL=2;
26         Status=CANCEL;
27         Ensure=new JDialog(notepad,true);/*
28          * 这里的模式标志true的作用是使对话框处于notepad的上端,并且当对话框显示时进程处于停滞状态,
29          * 直到对话框不再显示为止。在本程序中,由于对对话框进行了事件监听处理,当对话框消失时状态标
30          * 志Status同时发生了变化,这样就可以在进程继续时获得新的Status值 */
31         Yes=new JButton("Yes");//3个按钮
32         No=new JButton("No");
33         Cancel=new JButton("Cancel");
34         Question=new JLabel("  Do you want to save changes to the file?");//1个label
35         ButtonPanel=new JPanel();//按钮托盘
36         TextPanel=new JPanel();//文本托盘
37         ButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER,16,10));//按钮居中上下间距16,左右间距10
38         TextPanel.setLayout(new BorderLayout());//充满
39         Ensure.setLayout(new BorderLayout());//充满
40         ButtonPanel.add(Yes);//3个按钮加入按钮托盘
41         ButtonPanel.add(No);
42         ButtonPanel.add(Cancel);
43         TextPanel.add(Question);//将文本加入文本托盘
44         Ensure.add(TextPanel,BorderLayout.CENTER);
45         Ensure.add(ButtonPanel,BorderLayout.SOUTH);
46         Ensure.setLocation(x, y);
47         Ensure.setSize(360, 140);
48         Ensure.setResizable(false);
49         TextPanel.setBackground(Color.WHITE);
50         Question.setFont(new Font(null,Font.PLAIN,16));
51         Question.setForeground(new Color(0,95,191));
52         Yes.setFocusable(false);
53         No.setFocusable(false);
54         Cancel.setFocusable(false);
55         Ensure.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
56         Ensure.addWindowListener(this);//窗口监听
57         Yes.addActionListener(this);//个按钮监听
58         No.addActionListener(this);
59         Cancel.addActionListener(this);
60     }
61     public void actionPerformed(ActionEvent e){
62         if(e.getSource()==Yes) Status=YES;
63         else if(e.getSource()==No) Status=NO;
64         else if(e.getSource()==Cancel) Status=CANCEL;
65         Ensure.setVisible(false);
66     }
67     public void windowClosing(WindowEvent e){
68         Status=CANCEL;
69         Ensure.setVisible(false);
70     }
71     public void windowActivated(WindowEvent e) {}
72     public void windowClosed(WindowEvent e) {}
73     public void windowDeactivated(WindowEvent e) {}
74     public void windowDeiconified(WindowEvent e) {}
75     public void windowIconified(WindowEvent e) {}
76     public void windowOpened(WindowEvent e) {}
77     
78     public static void main(String args[]){
79         JFrame a=new JFrame();
80         EnsureDialog c=new EnsureDialog(a,400,400);
81         c.Ensure.setVisible(true);
82     }
83 }
EnsureDialog.java

4、查找与替换对话框:主要负责查找与替换。其功能部分不在这里,这里只是界面部分。更多介绍请看代码:(可单独运行)

 1 package notepad;
 2 import java.awt.TextField;
 3 import javax.swing.ButtonGroup;
 4 import javax.swing.JButton;
 5 import javax.swing.JCheckBox;
 6 import javax.swing.JDialog;
 7 import javax.swing.JFrame;
 8 import javax.swing.JLabel;
 9 import javax.swing.JRadioButton;
10 //只是一个窗口,没有其他函数
11 public class FindAndReplace{
12     public JDialog Dialog;
13     public JButton FindNext,Replace,ReplaceAll,Finish;//4个按钮
14     public JCheckBox MatchCase;//1个CheckBox
15     public JRadioButton Up,Down;//1组单选按钮(上下)
16     public ButtonGroup DirectionGroup;
17     public JLabel FindWhat,ReplaceWith,Direction;//3个label
18     public TextField FindText,ReplaceText;//2个文本区
19     FindAndReplace(JFrame notepad){//构造函数
20         Dialog=new JDialog(notepad,"Find And Replace...",false);/*
21          * 与EnsureDialog不同的是,这里的模式标志false使对话框始终处于notepad的上端,但点击notepad
22          * 时notepad会继续处于活动状态,对话框则变成不活动状态 注意!!!*/
23         FindNext=new JButton("Find Next");//4个按钮实例
24         Replace=new JButton("Replace");
25         ReplaceAll=new JButton("Replace All");
26         Finish=new JButton("Finish");
27         MatchCase=new JCheckBox("Match Case",false);//1个CheckBox
28         Down=new JRadioButton("Down",true);//1组单选
29         Up=new JRadioButton("Up",false);
30         FindWhat=new JLabel("Find What:");//3个label
31         ReplaceWith=new JLabel("Replace With:");
32         Direction=new JLabel("Direction:");
33         FindText=new TextField("");//2个文本区
34         ReplaceText=new TextField("");
35         Dialog.setSize(380, 160);
36         Dialog.setResizable(false);
37         FindNext.setFocusable(false);//
38         Replace.setFocusable(false);
39         ReplaceAll.setFocusable(false);
40         MatchCase.setFocusable(false);
41         Finish.setFocusable(false);
42         Up.setFocusable(false);
43         Down.setFocusable(false);
44         DirectionGroup=new ButtonGroup();
45         Dialog.setLayout(null);
46         FindWhat.setBounds(10,12,80,22);
47         ReplaceWith.setBounds(10,42,80,22);
48         FindText.setBounds(95, 12, 160, 22);
49         ReplaceText.setBounds(95, 42, 160, 22);
50         FindNext.setBounds(265, 12, 98, 22);
51         Replace.setBounds(265, 42, 98, 22);
52         ReplaceAll.setBounds(265, 72, 98, 22);
53         Direction.setBounds(10, 72, 80, 22);
54         MatchCase.setBounds(6, 102, 98, 22);
55         Down.setBounds(95, 72, 80, 22);
56         Up.setBounds(175, 72, 80, 22);
57         Finish.setBounds(265, 102, 98, 22);
58         DirectionGroup.add(Up);//单选加入group
59         DirectionGroup.add(Down);
60         Dialog.add(FindWhat);
61         Dialog.add(MatchCase);
62         Dialog.add(FindText);
63         Dialog.add(FindNext);
64         Dialog.add(Direction);
65         Dialog.add(ReplaceWith);
66         Dialog.add(ReplaceText);
67         Dialog.add(Replace);
68         Dialog.add(ReplaceAll);
69         Dialog.add(Finish);
70         Dialog.add(Down);
71         Dialog.add(Up);
72     }
73     public static void main(String args[]){
74         JFrame a=new JFrame();
75         FindAndReplace c=new FindAndReplace(a);
76         c.Dialog.setVisible(true);
77     }
78 }
FindAndReplace.java

 5、字体选择对话框:主要负责字体设置。更多介绍请看代码:(可单独运行)

  1 package notepad;
  2 import java.awt.Font;
  3 import java.awt.GraphicsEnvironment;
  4 import java.awt.List;
  5 import java.awt.event.ActionEvent;
  6 import java.awt.event.ActionListener;
  7 import java.awt.event.ItemEvent;
  8 import java.awt.event.ItemListener;
  9 import java.awt.event.WindowEvent;
 10 import java.awt.event.WindowListener;
 11 import java.io.RandomAccessFile;
 12 
 13 import javax.swing.JButton;
 14 import javax.swing.JCheckBox;
 15 import javax.swing.JDialog;
 16 import javax.swing.JFrame;
 17 import javax.swing.JTextArea;
 18 
 19 public class FontDialog implements ItemListener, ActionListener, WindowListener{
 20     public JDialog Dialog;
 21     public JCheckBox Bold,Italic;//2个CheckBox用于选择粗细和倾斜
 22     public List Size,Name;//2个list用于列出字型和大小
 23     public int FontName;
 24     public int FontStyle;
 25     public int FontSize;
 26     public JButton OK,Cancel;//2个按钮
 27     public JTextArea Text;//1个文本编辑区
 28     private RandomAccessFile file;//存储字体文件
 29     FontDialog(JFrame notepad, int x, int y){//构造函数
 30         GraphicsEnvironment g=GraphicsEnvironment.getLocalGraphicsEnvironment(); 
 31         String name[]=g.getAvailableFontFamilyNames();//获得系统字体
 32         Bold=new JCheckBox("Bold",false);//粗细倾斜设为false
 33         Italic=new JCheckBox("Italic",false);
 34         Dialog=new JDialog(notepad,"Font...",true);
 35         Text=new JTextArea("字体预览用例\n9876543210\nAaBbCcXxYyZz");
 36         OK=new JButton("OK");
 37         Cancel=new JButton("Cancel");
 38         Size=new List();//实例化字形和大小列表
 39         Name=new List();
 40         int i=0;
 41         Name.add("Default Value");
 42         for(i=0;i<name.length;i++) Name.add(name[i]);//名字加进list
 43         for(i=8;i<257;i++) Size.add(String.valueOf(i));//把字体加进list
 44         try {//初始化信息,从保存文件读取
 45             file=new RandomAccessFile("D:\\fontData.txt","rw");
 46             if(file.length()!=0){
 47                 FontName=file.readInt();
 48                 FontStyle=file.readInt();
 49                 FontSize=file.readInt();
 50             }else{
 51                 FontName=0;
 52                 FontStyle=0;
 53                 FontSize=0;
 54             }
 55             if(file!=null)file.close();
 56             //System.out.print(file.readInt()+" ");
 57             //System.out.print(file.readInt()+" ");
 58             //System.out.print(file.readInt()+" ");
 59         } catch (Exception e) {
 60             e.printStackTrace();
 61         } 
 62         Dialog.setLayout(null);
 63         Dialog.setLocation(x, y);
 64         Dialog.setSize(480, 306);
 65         Dialog.setResizable(false);
 66         OK.setFocusable(false);
 67         Cancel.setFocusable(false);
 68         Bold.setFocusable(false);
 69         Bold.setSelected(FontStyle%2==1);
 70         Italic.setFocusable(false);
 71         Italic.setSelected(FontStyle/2==1);
 72         Name.setFocusable(false);
 73         Size.setFocusable(false);
 74         Name.setBounds(10, 10, 212, 259);
 75         Dialog.add(Name);
 76         Bold.setBounds(314, 10, 64, 22);
 77         Dialog.add(Bold);
 78         Italic.setBounds(388, 10, 64, 22);
 79         Dialog.add(Italic);
 80         Size.setBounds(232, 10, 64, 259);
 81         Dialog.add(Size);
 82         Text.setBounds(306, 40, 157, 157);
 83         Dialog.add(Text);
 84         OK.setBounds(306, 243, 74, 26);
 85         Dialog.add(OK);
 86         Cancel.setBounds(390, 243, 74, 26);
 87         Dialog.add(Cancel);
 88         Name.select(FontName);//初始化列表选择!!!!
 89         Size.select(FontSize);
 90         Text.setFont(getFont());//初始化文本区字体形式
 91         Dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
 92         Name.addItemListener(this);//列表和checkbox是item监听
 93         Size.addItemListener(this);
 94         Bold.addItemListener(this);
 95         Italic.addItemListener(this);
 96         OK.addActionListener(this);//按钮是动作监听
 97         Cancel.addActionListener(this);
 98         Dialog.addWindowListener(this);//dialog是窗口监听
 99     }
100     public void itemStateChanged(ItemEvent e) {//item监听(只需改变文本区字体样式)
101         Text.setFont(getFont());
102     }
103     public void actionPerformed(ActionEvent e) {//窗口动作监听
104         if(e.getSource()==OK){//若是ok则全部更新
105             FontName=Name.getSelectedIndex();
106             FontStyle=getStyle();//粗细和倾斜
107             FontSize=Size.getSelectedIndex();
108             Dialog.setVisible(false);
109             try {
110                 file=new RandomAccessFile("D:\\fontData.txt","rw");
111                 file.writeInt(FontName);
112                 file.writeInt(FontStyle);
113                 file.writeInt(FontSize);
114                 if(file!=null)file.close();
115             } catch (Exception e1) {
116                 e1.printStackTrace();
117             }            
118         }
119         else cancel();
120     }
121     public void windowClosing(WindowEvent e) {//窗口关闭
122         cancel();
123     }
124     public Font getFont(){//获得字体函数
125         if(Name.getSelectedIndex()==0) return new Font("新宋体",getStyle(),Size.getSelectedIndex()+8);//大小是从8开始的
126         else return new Font(Name.getSelectedItem(),getStyle(),Size.getSelectedIndex()+8);
127     }
128     public void cancel(){//cancel函数
129         Name.select(FontName);//将2个列表还原,字体粗细还原,设为不可视
130         Size.select(FontSize);
131         setStyle();
132         Text.setFont(getFont());
133         Dialog.setVisible(false);
134     }
135     public void setStyle(){//设置字体粗细(由FontStyle推得00,01,10,11)
136         if(FontStyle==0 || FontStyle==2) Bold.setSelected(false);
137         else Bold.setSelected(true);
138         if(FontStyle==0 || FontStyle==1) Italic.setSelected(false);
139         else Italic.setSelected(true);
140     }
141     public int getStyle(){//获得粗细数值(00,01,10,11)=FontStyle
142         int bold=0,italic=0;
143         if(Bold.isSelected()) bold=1;
144         if(Italic.isSelected()) italic=1;
145         return bold+italic*2;
146     }
147     public void windowActivated(WindowEvent arg0) {}
148     public void windowClosed(WindowEvent arg0) {}
149     public void windowDeactivated(WindowEvent arg0) {}
150     public void windowDeiconified(WindowEvent arg0) {}
151     public void windowIconified(WindowEvent arg0) {}
152     public void windowOpened(WindowEvent arg0) {}
153 
154     public static void main(String args[]){
155        JFrame a=new JFrame();
156        FontDialog c=new FontDialog(a,400,400);
157        c.Dialog.setVisible(true);
158     }
159 }
FontDialog.java

6、MenuList类:负责把menu的各个功能集成到这个类中单独处理,这样很方便对menu进行扩展(这里只是各个元件的组合,其监听实现不在这里,不能单独运行出现界面)

  1 package notepad;
  2 import javax.swing.JCheckBoxMenuItem;
  3 import javax.swing.JMenu;
  4 import javax.swing.JMenuBar;
  5 import javax.swing.JMenuItem;
  6 import javax.swing.KeyStroke;
  7 
  8 public class MenuList{
  9     public JMenuBar Menu;
 10     public JMenu File, Edit, App,Run,TXL,View, Help;
 11     public JMenuItem
 12         New,Open,Save,SaveAs,Print,Exit,//File
 13         Undo,Redo,Cut,Copy,Paste,Delete,SelectAll,FindAndReplace,//Edit
 14         HuiWen,FanYi,TongJi,QiuHe,//App
 15         Build,Go,//Run
 16         TXL_1,TXL_2,//TXL
 17         Font,Color,//View
 18         ViewHelp,AboutNotepad;//Help
 19     public JCheckBoxMenuItem WordWrap,Truncation;
 20     MenuList(){
 21         Menu=new JMenuBar();
 22         //File//////////////////////////////////////////////
 23         File=new JMenu(" File ");
 24         New=new JMenuItem("New");
 25         Open=new JMenuItem("Open...");
 26         Save=new JMenuItem("Save");
 27         SaveAs=new JMenuItem("Save As...");
 28         Print=new JMenuItem("Print...");
 29         Exit=new JMenuItem("Exit");
 30         ////Edit////////////////////////////////////////////
 31         Edit=new JMenu(" Edit ");
 32         Undo=new JMenuItem("Undo");
 33         Redo=new JMenuItem("Redo");
 34         Cut=new JMenuItem("Cut");
 35         Copy=new JMenuItem("Copy");
 36         Paste=new JMenuItem("Paste");
 37         Delete=new JMenuItem("Delete");
 38         SelectAll=new JMenuItem("Select All");
 39         FindAndReplace=new JMenuItem("Find And Replace...");
 40         Undo.setEnabled(false);
 41         Redo.setEnabled(false);
 42         //App///////////////////////////////////////////////
 43         App=new JMenu(" App ");
 44         HuiWen=new JMenuItem("HuiWen");
 45         FanYi=new JMenuItem("FanYi");
 46         TongJi=new JMenuItem("TongJi");
 47         QiuHe=new JMenuItem("QiuHe");
 48         //Run//////////////////////////////////////////////
 49         Run=new JMenu(" Run ");
 50         Build=new JMenuItem("Build");
 51         Go=new JMenuItem("Go");
 52         Build.setEnabled(false);
 53         Go.setEnabled(false);
 54         //TXL//////////////////////////////////////////////
 55         TXL=new JMenu(" TongXunLu ");
 56         TXL_1=new JMenuItem("详细.....");
 57         TXL_2=new JMenuItem("设置路径");
 58         //View/////////////////////////////////////////////
 59         View=new JMenu(" View ");
 60         WordWrap=new JCheckBoxMenuItem("Word Wrap",true);
 61         Truncation=new JCheckBoxMenuItem("Truncation",false);
 62         Font=new JMenuItem("Font...");
 63         Color=new JMenuItem("Color...");
 64         //Help/////////////////////////////////////////////
 65         Help=new JMenu(" Help ");
 66         ViewHelp=new JMenuItem("View Help...");
 67         AboutNotepad=new JMenuItem("About Notepad...");
 68         
 69         Help.add(ViewHelp);
 70         Help.add(AboutNotepad);
 71         View.add(WordWrap);
 72         View.add(Truncation);
 73         View.addSeparator();
 74         View.add(Font);
 75         View.add(Color);
 76         TXL.add(TXL_1);
 77         TXL.add(TXL_2);
 78         Run.add(Build);
 79         Run.add(Go);
 80         App.add(HuiWen);
 81         App.add(FanYi);
 82         App.add(TongJi);
 83         App.add(QiuHe);
 84         Edit.add(Undo);
 85         Edit.add(Redo);
 86         Edit.addSeparator();
 87         Edit.add(Cut);
 88         Edit.add(Copy);
 89         Edit.add(Paste);
 90         Edit.add(Delete);
 91         Edit.addSeparator();
 92         Edit.add(SelectAll);
 93         Edit.add(FindAndReplace);
 94         File.add(New);
 95         File.add(Open);
 96         File.addSeparator();
 97         File.add(Save);
 98         File.add(SaveAs);
 99         File.addSeparator();
100         File.add(Print);
101         File.add(Exit);
102         Menu.add(File);
103         Menu.add(Edit);
104         Menu.add(App);
105         Menu.add(Run);
106         Menu.add(TXL);
107         Menu.add(View);
108         Menu.add(Help);
109         New.setAccelerator(KeyStroke.getKeyStroke('N',128));
110         Open.setAccelerator(KeyStroke.getKeyStroke('O',128));
111         Save.setAccelerator(KeyStroke.getKeyStroke('S',128));
112         Print.setAccelerator(KeyStroke.getKeyStroke('P',128));
113         Undo.setAccelerator(KeyStroke.getKeyStroke('Z',128));
114         Redo.setAccelerator(KeyStroke.getKeyStroke('Y',128));
115         Cut.setAccelerator(KeyStroke.getKeyStroke('X',128));
116         Copy.setAccelerator(KeyStroke.getKeyStroke('C',128));
117         Paste.setAccelerator(KeyStroke.getKeyStroke('V',128));
118         Build.setAccelerator(KeyStroke.getKeyStroke('B',128));
119         Go.setAccelerator(KeyStroke.getKeyStroke('G',128));
120         Delete.setAccelerator(KeyStroke.getKeyStroke(127,0));
121         SelectAll.setAccelerator(KeyStroke.getKeyStroke('A',128));
122     }
123 }
MenuList.java

7、 TextArea类:主要的文本编辑区类,同时集成上面的menu类,基本构成该软件的主要界面和功能的封装。把menu的监听函数需要用的函数封装了一下。具体请看代码,不能单独运行出现界面:

  1 package notepad;
  2 import java.awt.Toolkit;
  3 import java.awt.datatransfer.Clipboard;
  4 import java.awt.datatransfer.DataFlavor;
  5 import java.awt.datatransfer.Transferable;
  6 import java.awt.event.ActionEvent;
  7 import java.awt.event.ActionListener;
  8 import java.awt.event.ItemEvent;
  9 import java.awt.event.ItemListener;
 10 import java.awt.event.MouseEvent;
 11 import java.awt.event.MouseListener;
 12 import java.io.BufferedWriter;
 13 import java.io.FileReader;
 14 import java.io.FileWriter;
 15 import java.io.IOException;
 16 import javax.swing.JFrame;
 17 import javax.swing.JMenuItem;
 18 import javax.swing.JPopupMenu;
 19 import javax.swing.JScrollPane;
 20 import javax.swing.JTextArea;
 21 import javax.swing.event.MenuEvent;
 22 import javax.swing.event.MenuListener;
 23 import javax.swing.event.UndoableEditEvent;
 24 import javax.swing.event.UndoableEditListener;
 25 import javax.swing.undo.UndoManager;
 26 
 27 import toolBarTest.ToolBar;
 28 
 29 public class TextArea extends JTextArea implements MouseListener,UndoableEditListener,
 30 MenuListener,ActionListener,ItemListener{
 31     private static final long serialVersionUID = 1L;
 32     public boolean Saved;//标记变量,看是否保存
 33     public String Name,Path;
 34     public JScrollPane Pane;//分隔条
 35     public JPopupMenu Popup;//弹出菜单
 36     public JMenuItem Redo,Undo,Cut,Copy,Paste,Delete,SelectAll,FindAndReplace;//弹出菜单元素
 37     public UndoManager Manager;//
 38     public MenuList menu;//自定义菜单
 39     ToolBar toolbar;//自定义工具条
 40     public FindAndReplace find;//查找替换菜单元
 41     TextArea(JFrame notepad,int x,int y){//构造函数(父类,x,y)
 42         super();
 43         Saved=true;//构造时,设为已保存
 44         Name=null;
 45         Path=null;
 46         Popup=new JPopupMenu();
 47         Undo=new JMenuItem("  Undo");
 48         Redo=new JMenuItem("  Redo");
 49         Cut=new JMenuItem("  Cut");
 50         Copy=new JMenuItem("  Copy");
 51         Paste=new JMenuItem("  Paste");
 52         Delete=new JMenuItem("  Delete");
 53         SelectAll=new JMenuItem("  Select All");
 54         FindAndReplace=new JMenuItem("  Find And Replace...");
 55         Pane=new JScrollPane(this);
 56         Manager=new UndoManager();
 57         menu=new MenuList();
 58         toolbar=new ToolBar();//工具条
 59         find=new FindAndReplace(notepad);//初始化
 60         find.Dialog.setLocation(x,y);
 61         Undo.setEnabled(false);
 62         Redo.setEnabled(false);
 63         setLineWrap(true);//自动换行
 64         setWrapStyleWord(true);//自动换行换单词
 65         Manager.setLimit(-1);//无限次返回
 66         Popup.add(Undo);
 67         Popup.add(Redo);
 68         Popup.addSeparator();
 69         Popup.add(Cut);
 70         Popup.add(Copy);
 71         Popup.add(Paste);
 72         Popup.add(Delete);
 73         Popup.addSeparator();
 74         Popup.add(SelectAll);
 75         Popup.add(FindAndReplace);
 76         add(Popup);//将元素加入弹出窗口,将弹出窗口加入文本区
 77         menu.Edit.addMenuListener(this);//菜单-编辑-菜单监听
 78         menu.WordWrap.addItemListener(this);//菜单-换行-元素监听
 79         menu.Truncation.addItemListener(this);//菜单-文字换行-元素监听
 80         getDocument().addUndoableEditListener(this);//文本-撤销恢复监听
 81         addMouseListener(this);//鼠标监听
 82         find.FindNext.addActionListener(this);//find的4个动作监听
 83         find.Replace.addActionListener(this);
 84         find.ReplaceAll.addActionListener(this);
 85         find.Finish.addActionListener(this);
 86     }
 87     public void saveFile(){//保存文件
 88         try {
 89             FileWriter fw = new FileWriter(Path+Name,false);
 90             BufferedWriter bw=new BufferedWriter(fw);
 91             bw.write(getText());
 92             bw.close();
 93             fw.close();
 94             Saved=true;
 95         } catch (IOException e){}
 96     }
 97     public void openFile(){//打开文件
 98         try {
 99             int c;
100             StringBuffer sb=new StringBuffer();
101             FileReader fr=new FileReader(Path+Name);
102             setText(null);
103             while((c=fr.read())!=-1)
104                 sb.append((char)c);
105             setText(sb.toString());
106             Saved=true;
107             fr.close();
108             Undo.setEnabled(false);//刚打开的撤销和重做都设成false
109             Redo.setEnabled(false);
110             menu.Undo.setEnabled(false);
111             menu.Redo.setEnabled(false);
112             toolbar.Undo.setEnabled(false);
113             toolbar.Redo.setEnabled(false);
114         }
115         catch (IOException e){}
116     }
117     public void delete(){//删除
118         int start=getSelectionStart();
119         int end=getSelectionEnd();
120         replaceRange("",start,end);
121     }
122     public int lastOf(String s1,int i){//从后往前查找
123         String s=getText();
124         if(find.MatchCase.isSelected()) return s.lastIndexOf(s1,i);
125         else{
126             s=s.toLowerCase();
127             return s.lastIndexOf(s1.toLowerCase(),i);
128         }
129     }
130     public int nextOf(String s1,int i){//从前往后查找
131         String s=getText();
132         if(find.MatchCase.isSelected()) return s.indexOf(s1,i);
133         else{
134             s=s.toLowerCase();
135             return s.indexOf(s1.toLowerCase(),i);
136         }
137     }
138     public void actionPerformed(ActionEvent e){//find&&replace
139         Object obj=e.getSource();
140         if(obj==find.Finish) find.Dialog.setVisible(false);//结束时让窗口不可见
141         String s1=find.FindText.getText();
142         String s2=find.ReplaceText.getText();
143         int len1=s1.length(),len2=s2.length();
144         if(len1<1) return;
145         int head=getSelectionStart(),rear=getSelectionEnd();//J函数,获取选中区开始和结束
146         if(obj==find.Replace){
147             if(head<rear) replaceRange(s2,head,rear);//J函数,把
148             else obj=find.FindNext;
149         }
150         if(obj==find.FindNext){//查找下一个
151             if(find.Up.isSelected()){//向上
152                 head=lastOf(s1,head-len1);
153                 if(head<0) return;
154                 select(head, head+len1);
155             }
156             else{//向下
157                 rear=nextOf(s1, rear);
158                 if(rear<0) return;
159                 select(rear,rear+len1);
160             }
161         }
162         else if(obj==find.ReplaceAll){
163             rear=0;
164             while(true){
165                 rear=nextOf(s1,rear);
166                 if(rear<0) return;
167                 replaceRange(s2,rear,rear+len1);
168                 rear=rear+len2;
169                 setCaretPosition(rear);
170             }
171         }
172     }
173     public void menuSelected(MenuEvent e){//和弹出菜单类似,不做详解
174         Clipboard Board=Toolkit.getDefaultToolkit().getSystemClipboard();
175         Transferable contents = Board.getContents(Board);
176         DataFlavor flavor = DataFlavor.stringFlavor;
177         if(contents.isDataFlavorSupported(flavor))
178             menu.Paste.setEnabled(true);
179         else
180             menu.Paste.setEnabled(false);
181         if(getSelectedText()!=null){
182             menu.Cut.setEnabled(true);
183             menu.Copy.setEnabled(true);
184             menu.Delete.setEnabled(true);
185         }
186         else{
187             menu.Cut.setEnabled(false);
188             menu.Copy.setEnabled(false);
189             menu.Delete.setEnabled(false);
190         }
191         if(getText().isEmpty()){
192             menu.SelectAll.setEnabled(false);
193             menu.FindAndReplace.setEnabled(false);
194         }
195         else{
196             menu.SelectAll.setEnabled(true);
197             menu.FindAndReplace.setEnabled(true);
198         }
199     }
200     public void undoableEditHappened(UndoableEditEvent e){//文本变化监听
201         Manager.addEdit(e.getEdit());
202         Saved=false;
203         menu.Undo.setEnabled(true);
204         menu.Redo.setEnabled(false);
205         Undo.setEnabled(true);
206         Redo.setEnabled(false);
207         toolbar.Undo.setEnabled(true);
208         toolbar.Redo.setEnabled(false);
209         menu.Go.setEnabled(false);
210     }
211     public void mouseReleased(MouseEvent e) {//鼠标释放监听
212         if(e.isPopupTrigger())
213         {
214             Clipboard Board=Toolkit.getDefaultToolkit().getSystemClipboard();//此类实现一种使用剪切/复制/粘贴操作传输数据的机制
215             Transferable contents = Board.getContents(Board);//定义为传输操作提供数据所使用的类的接口
216             DataFlavor flavor = DataFlavor.stringFlavor;//通常用于访问剪切板上的数据,或者在执行拖放操作时使用
217             if(contents.isDataFlavorSupported(flavor))//如果剪切板中有数据就把past激活
218                 Paste.setEnabled(true);
219             else
220                 Paste.setEnabled(false);
221             if(getSelectedText()!=null){//如果选中文本,就把剪切、复制、删除激活
222                 Cut.setEnabled(true);
223                 Copy.setEnabled(true);
224                 Delete.setEnabled(true);
225             }
226             else{
227                 Cut.setEnabled(false);
228                 Copy.setEnabled(false);
229                 Delete.setEnabled(false);
230             }
231             if(getText().isEmpty()){//如果没有文本,就把全选和查找替换封闭
232                 SelectAll.setEnabled(false);
233                 FindAndReplace.setEnabled(false);
234             }
235             else{
236                 SelectAll.setEnabled(true);
237                 FindAndReplace.setEnabled(true);
238             }
239             Popup.show(this,e.getX(),e.getY());//显示弹出窗口
240         }
241     }
242     public void itemStateChanged(ItemEvent e) {//换行监听器监听
243         if(e.getSource()==menu.WordWrap){
244             setLineWrap(menu.WordWrap.isSelected());
245             menu.Truncation.setEnabled(menu.WordWrap.isSelected());
246         }
247         else
248             setWrapStyleWord(!menu.Truncation.isSelected());
249     }
250     public void mousePressed(MouseEvent e) {}
251     public void mouseClicked(MouseEvent e) {}
252     public void mouseEntered(MouseEvent e) {}
253     public void mouseExited(MouseEvent e) {}
254     public void menuCanceled(MenuEvent e) {}
255     public void menuDeselected(MenuEvent e) {}
256 }
TextArea.java

8、Notepad类:主程序。实现各种监听。代码如下:

  1 package notepad;
  2 
  3 import java.awt.BorderLayout;
  4 import java.awt.Dimension;
  5 import java.awt.FileDialog;
  6 import java.awt.Image;
  7 import java.awt.Toolkit;
  8 import java.awt.event.ActionEvent;
  9 import java.awt.event.ActionListener;
 10 import java.awt.event.WindowEvent;
 11 import java.awt.event.WindowListener;
 12 import java.awt.print.PrinterException;
 13 import java.io.IOException;
 14 import java.io.RandomAccessFile;
 15 import javax.swing.JFrame;
 16 import javax.swing.JOptionPane;
 17 import tongxunlu.MyAddBook;
 18 import toolBarTest.ToolBar;
 19 import App.CountString;
 20 import App.FQiuHe;
 21 import App.HuiWen;
 22 import App.NumExchangeEnglish;
 23 import BianYi.Commond;
 24 
 25 public class Notepad implements ActionListener,WindowListener{
 26     static Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕大小
 27     static Image icon=Toolkit.getDefaultToolkit().getImage("50.png");//程序图标
 28     static JFrame notepad;//总窗口
 29     EnsureDialog ensure;//确定窗口
 30     TextArea text;//文件编辑区(主要元素都在这里)
 31     FileDialog dialog;//文件对话框
 32     FontDialog font;//字体对话框
 33     ColorDialog color;//颜色对话框
 34     AboutDialog about;//about对话框
 35     MyAddBook  tongXunLu;//通讯录对话框
 36     private RandomAccessFile file;//存储通讯录地址文件夹
 37     Commond C;//编译结果窗口
 38     Notepad(){
 39         notepad=new JFrame("201226100108-李涛-java程序设计综合实验");//界面
 40         dialog=new FileDialog(notepad);//文件对话框
 41         text=new TextArea(notepad,screen.width/2-190,screen.height/2-90);//文本区 
 42         ensure=new EnsureDialog(notepad,screen.width/2-180,screen.height/2-80);//确认对话框
 43         font=new FontDialog(notepad,screen.width/2-240,screen.height/2-150);//字体对话框
 44         color=new ColorDialog(notepad,screen.width/2-205,screen.height/2-110);//颜色对话框
 45         about=new AboutDialog(notepad,screen.width/2-140,screen.height/2-100);//about对话框
 46         tongXunLu=new MyAddBook();//通讯录对话框
 47         C=new Commond(600,400,100,100);//编译运行对话框
 48         notepad.setJMenuBar(text.menu.Menu);
 49         notepad.setLayout(new BorderLayout());//
 50         notepad.add("Center",text.Pane);
 51         notepad.add("North",text.toolbar);
 52         notepad.setSize(840,480);//设置大小
 53         notepad.setLocation(screen.width/2-420,screen.height/2-240);//设置位置
 54         notepad.setMinimumSize(new Dimension(185,185));//设置最小大小
 55         notepad.setIconImage(icon);//设置图标
 56         notepad.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//关闭
 57         notepad.addWindowListener(this);//窗口监听%%%%%%%
 58         text.setFont(font.getFont());//字体初始化
 59         text.setForeground(color.NFC);//前景窗口颜色
 60         text.setBackground(color.NBC);//背景窗口颜色
 61         text.setSelectedTextColor(color.SFC);//前景字体颜色
 62         text.setSelectionColor(color.SBC);//背景字体颜色
 63         text.menu.Save.addActionListener(this);//所有监听.......
 64         text.menu.SaveAs.addActionListener(this);
 65         text.menu.Open.addActionListener(this);
 66         text.menu.New.addActionListener(this);
 67         text.menu.Print.addActionListener(this);
 68         text.menu.Exit.addActionListener(this);
 69         text.menu.Undo.addActionListener(this);
 70         text.menu.Redo.addActionListener(this);
 71         text.menu.Cut.addActionListener(this);
 72         text.menu.Copy.addActionListener(this);
 73         text.menu.Paste.addActionListener(this);
 74         text.menu.Delete.addActionListener(this);
 75         text.menu.SelectAll.addActionListener(this);
 76         text.menu.FindAndReplace.addActionListener(this);
 77         text.menu.WordWrap.addActionListener(this);
 78         text.menu.Truncation.addActionListener(this);
 79         text.menu.Font.addActionListener(this);
 80         text.menu.Color.addActionListener(this);
 81         text.menu.ViewHelp.addActionListener(this);
 82         text.menu.AboutNotepad.addActionListener(this);
 83         text.menu.HuiWen.addActionListener(this);//app
 84         text.menu.FanYi.addActionListener(this);
 85         text.menu.TongJi.addActionListener(this);
 86         text.menu.QiuHe.addActionListener(this);
 87         text.menu.TXL_1.addActionListener(this);//TXL
 88         text.menu.TXL_2.addActionListener(this);
 89         text.menu.Build.addActionListener(this);//run
 90         text.menu.Go.addActionListener(this);
 91         text.toolbar.New.addActionListener(this);//toolbar
 92         text.toolbar.Open.addActionListener(this);
 93         text.toolbar.Save.addActionListener(this);
 94         text.toolbar.Build.addActionListener(this);
 95         text.toolbar.Run.addActionListener(this);
 96         text.toolbar.Undo.addActionListener(this);
 97         text.toolbar.Redo.addActionListener(this);
 98         text.Undo.addActionListener(this);//弹出窗口监听
 99         text.Redo.addActionListener(this);
100         text.Cut.addActionListener(this);
101         text.Copy.addActionListener(this);
102         text.Paste.addActionListener(this);
103         text.Delete.addActionListener(this);
104         text.SelectAll.addActionListener(this);
105         text.FindAndReplace.addActionListener(this);
106     }
107     public void windowClosing(WindowEvent e) {//关闭按钮重定义
108         if(text.Saved){ 
109             if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
110                 System.exit(0);
111             else return;
112         }
113         else{
114             if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
115                 ensure.Ensure.setVisible(true);//确认窗口打开    
116             else return;
117         }
118         if(ensure.Status==ensure.YES && saveFile()) System.exit(0);
119         else if(ensure.Status==ensure.NO) System.exit(0);
120     }
121     public void actionPerformed(ActionEvent e){//
122         Object obj=e.getSource();
123         if(obj==text.menu.Save || obj==text.toolbar.Save) saveFile();//保存
124         else if(obj==text.menu.SaveAs) saveAsFile();//另存为
125         else if(obj==text.menu.New || obj==text.toolbar.New){//新建
126             if(!(text.Saved)){//若没有保存
127                 ensure.Ensure.setVisible(true);
128                 if(ensure.Status==ensure.YES && saveFile()){}
129                 else if(ensure.Status==ensure.NO){}
130                 else return;
131             }
132             newFile();
133         }
134         else if(obj==text.menu.Open || obj==text.toolbar.Open){//打开
135             if(!(text.Saved)){
136                 ensure.Ensure.setVisible(true);
137                 if(ensure.Status==ensure.YES && saveFile()){}
138                 else if(ensure.Status==ensure.NO){}
139                 else return;
140             }
141             openFile();
142         }
143         else if(obj==text.menu.Print){//打印
144             try {
145                 text.print();
146             } catch (PrinterException pe){}
147         }
148         else if(obj==text.menu.Exit){//退出
149             if(text.Saved){ 
150                 if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
151                     System.exit(0);
152                 else return;
153             }
154             else{
155                 if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
156                     ensure.Ensure.setVisible(true);//确认窗口打开    
157                 else return;
158             }
159             if(ensure.Status==ensure.YES && saveFile()) System.exit(0);
160             else if(ensure.Status==ensure.NO) System.exit(0);
161         }
162         else if(obj==text.menu.Undo || obj==text.Undo || obj==text.toolbar.Undo){//返回一步
163             text.Manager.undo();
164             text.Saved=false;
165             text.menu.Redo.setEnabled(true);
166             text.Redo.setEnabled(true);
167             text.toolbar.Redo.setEnabled(true);
168             if(!text.Manager.canUndo()){
169                 text.menu.Undo.setEnabled(false);
170                 text.Undo.setEnabled(false);
171                 text.toolbar.Undo.setEnabled(false);
172             }
173         }
174         else if(obj==text.menu.Redo || obj==text.Redo || obj==text.toolbar.Redo){//前进一步
175             text.Manager.redo();
176             text.Saved=false;
177             text.menu.Undo.setEnabled(true);
178             text.Undo.setEnabled(true);
179             text.toolbar.Undo.setEnabled(true);
180             if(!text.Manager.canRedo()){
181                 text.menu.Redo.setEnabled(false);
182                 text.Redo.setEnabled(false);
183                 text.toolbar.Redo.setEnabled(false);
184             }
185         }
186         else if(obj==text.Cut || obj==text.menu.Cut){//剪切
187             text.cut();
188         }
189         else if(obj==text.Copy || obj==text.menu.Copy){//复制
190             text.copy();
191         }
192         else if(obj==text.Paste || obj==text.menu.Paste){//粘贴
193             text.paste();
194         }
195         else if(obj==text.Delete || obj==text.menu.Delete){//删除
196             text.delete();
197         }
198         else if(obj==text.SelectAll || obj==text.menu.SelectAll){//全选
199             text.selectAll();
200         }
201         else if(obj==text.FindAndReplace || obj==text.menu.FindAndReplace){//查找替换
202             text.find.Dialog.setVisible(true);
203         }
204         
205         else if(obj==text.menu.HuiWen){//回文串
206             HuiWen a=new HuiWen();
207         }else if(obj==text.menu.FanYi){//翻译
208             NumExchangeEnglish a=new NumExchangeEnglish();
209         }else if(obj==text.menu.TongJi){//统计
210             if(text.Name==null){saveFile();text.Saved=true;}
211             else if(!text.Saved){saveFile();text.Saved=true;}
212             try {
213                 CountString a=new CountString(text.Path+text.Name);
214             } catch(IOException e1){}
215         }else if(obj==text.menu.QiuHe){//求和
216             if(text.Name==null){saveFile();text.Saved=true;}
217             else if(!text.Saved){saveFile();text.Saved=true;}
218             FQiuHe a=new FQiuHe(text.Path+text.Name,Notepad.notepad);
219         }
220         else if(obj==text.menu.TXL_1){//通讯录
221             if(tongXunLu==null)tongXunLu=new MyAddBook();
222             tongXunLu.frame.setVisible(true);
223         }else if(obj==text.menu.TXL_2){//更改路径
224             if(tongXunLu==null)tongXunLu=new MyAddBook();
225             String path,name;
226             dialog.setMode(FileDialog.SAVE);
227             dialog.setTitle("Change As...");
228             dialog.setFile(tongXunLu.Name);
229             dialog.setVisible(true);
230             path=dialog.getDirectory();
231             name=dialog.getFile();
232             if(name!=null){
233                 tongXunLu.changeRoad(path,name);//改变路径
234                 JOptionPane.showMessageDialog(notepad,"路径已修改至: "+path+name);
235             }
236         }else if(obj==text.menu.Build || obj==text.toolbar.Build){//编译
237             String s;
238             if(!text.Saved)saveFile();
239             try {
240                 s=C.getInfoDOS(text.Name,text.Path,false);Commond.show.addStr(s);
241                 text.menu.Go.setEnabled(true);//将按钮激活
242                 text.toolbar.Run.setEnabled(true);
243             } catch (IOException | InterruptedException e1) {
244                 e1.printStackTrace();
245             }
246         }else if(obj==text.menu.Go || obj==text.toolbar.Run){//运行
247             String s;
248             try {
249                 s=C.getInfoDOS(text.Name,text.Path,true);Commond.show.addStr(s);
250             } catch (IOException | InterruptedException e1){
251                 e1.printStackTrace();
252             }
253         }
254         else if(obj==text.menu.Font){//字体
255             font.Dialog.setVisible(true);
256             if(text.getFont()!=font.getFont())
257                 text.setFont(font.getFont());
258         }
259         else if(obj==text.menu.Color){//颜色
260             color.Dialog.setVisible(true);
261             text.setForeground(color.NFC);
262             text.setBackground(color.NBC);
263             text.setSelectedTextColor(color.SFC);
264             text.setSelectionColor(color.SBC);
265             text.setCaretColor(color.NFC);
266         }
267         else if(obj==text.menu.AboutNotepad){//about
268             about.Dialog.setVisible(true);
269         }
270     }
271     
272     public boolean saveFile(){//保存函数
273         if(text.Name==null){
274             dialog.setMode(FileDialog.SAVE);
275             dialog.setTitle("Save As...");
276             dialog.setFile("Untitled.txt");
277             dialog.setVisible(true);
278             text.Path=dialog.getDirectory();
279             text.Name=dialog.getFile();
280         }
281         if(text.Name==null) return false;
282         text.saveFile();
283         notepad.setTitle(text.Name+" - Notepad");
284         if(text.Name.endsWith("java")){//是java文件
285             text.menu.Build.setEnabled(true);
286             text.menu.Go.setEnabled(false);
287             text.toolbar.Build.setEnabled(true);
288             text.toolbar.Run.setEnabled(false);
289         }
290         return true;
291     }
292     public void saveAsFile(){//另存函数
293         String path=text.Path;
294         String name=text.Name;
295         dialog.setMode(FileDialog.SAVE);
296         dialog.setTitle("Save As...");
297         if(text.Name==null)
298             dialog.setFile("Untitled.txt");
299         else dialog.setFile(text.Name);
300         dialog.setVisible(true);
301         text.Path=dialog.getDirectory();
302         text.Name=dialog.getFile();
303         if(text.Name!=null){
304             text.saveFile();
305             notepad.setTitle(text.Name+" - Notepad");
306         }
307         else{
308             text.Name=name;
309             text.Path=path;
310         }
311         if(text.Name.endsWith("java")){//是java文件
312             text.menu.Build.setEnabled(true);
313             text.menu.Go.setEnabled(false);
314             text.toolbar.Build.setEnabled(true);
315             text.toolbar.Run.setEnabled(false);
316         }
317     }
318     public void openFile(){//打开函数
319         String path=text.Path;
320         String name=text.Name;
321         dialog.setTitle("Open...");
322         dialog.setMode(FileDialog.LOAD);
323         dialog.setVisible(true);
324         text.Path=dialog.getDirectory();
325         text.Name=dialog.getFile();
326         if(text.Name!=null){
327             text.openFile();
328             notepad.setTitle(text.Name+" - Notepad");
329         }
330         else{
331             text.Name=name;
332             text.Path=path;
333         }
334         if(text.Name.endsWith("java")){//是java文件
335             text.menu.Build.setEnabled(true);
336             text.menu.Go.setEnabled(false);
337             text.toolbar.Build.setEnabled(true);
338             text.toolbar.Run.setEnabled(false);
339         }
340     }
341     public void newFile(){//新建
342         text.Path=null;
343         text.Name=null;
344         text.setText(null);
345         notepad.setTitle("Notepad");
346         text.Saved=true;
347         text.Undo.setEnabled(false);
348         text.Redo.setEnabled(false);
349         text.menu.Undo.setEnabled(false);
350         text.menu.Redo.setEnabled(false);
351         text.menu.Build.setEnabled(false);
352         text.menu.Go.setEnabled(false);
353         text.toolbar.Build.setEnabled(false);
354         text.toolbar.Run.setEnabled(false);
355     }
356     public static void main(String s[]){
357         System.setProperty("java.awt.im.style","on-the-spot"); //去除输入中文时的浮动框
358         Notepad np=new Notepad();
359         Notepad.notepad.setVisible(true);
360     }
361     public void windowActivated(WindowEvent arg0){}
362     public void windowClosed(WindowEvent arg0){}
363     public void windowDeactivated(WindowEvent arg0){}
364     public void windowDeiconified(WindowEvent arg0){}
365     public void windowIconified(WindowEvent arg0){}
366     public void windowOpened(WindowEvent arg0){}
367 }
Notepad.java

toolBarTest包

1、JToolBar类:主要是工具条的元件组合,监听在notepad类内实现。可单独运行查看效果:

 1 package toolBarTest;
 2 import java.awt.BorderLayout;
 3 import java.awt.Color;
 4 import java.awt.Container;
 5 import java.awt.FlowLayout;
 6 
 7 import javax.swing.BorderFactory;
 8 import javax.swing.Icon;
 9 import javax.swing.ImageIcon;
10 import javax.swing.JButton;
11 import javax.swing.JFrame;
12 import javax.swing.JTextArea;
13 import javax.swing.JToolBar;
14 
15 public class ToolBar extends JToolBar{
16     public FgButton New,Open,Save,Build,Run,Undo,Redo;
17     public ToolBar(){
18         super();
19         setBackground(new Color(255,255,255));//把条设成白色
20         addToolBar();
21     }
22     private void addToolBar() {
23         // 工具条
24         setLayout(new FlowLayout(FlowLayout.LEFT));
25         New=new FgButton(new ImageIcon(getClass().getResource("new.png")),"新建文件");
26         Open=new FgButton(new ImageIcon(getClass().getResource("open.png")),"打开文件");
27         Save=new FgButton(new ImageIcon(getClass().getResource("save.png")),"保存文件");
28         Build=new FgButton(new ImageIcon(getClass().getResource("build.png")),"编译");
29         Run=new FgButton(new ImageIcon(getClass().getResource("run.png")),"运行");
30         Undo=new FgButton(new ImageIcon(getClass().getResource("undo.png")),"返回");
31         Redo=new FgButton(new ImageIcon(getClass().getResource("redo.png")),"重做");
32         
33         New.setBorder(BorderFactory.createEmptyBorder());
34         Open.setBorder(BorderFactory.createEmptyBorder());
35         Save.setBorder(BorderFactory.createEmptyBorder());
36         Build.setBorder(BorderFactory.createEmptyBorder());
37         Run.setBorder(BorderFactory.createEmptyBorder());
38         Undo.setBorder(BorderFactory.createEmptyBorder());
39         Redo.setBorder(BorderFactory.createEmptyBorder());
40         
41         Build.setEnabled(false);
42         Run.setEnabled(false);
43         Undo.setEnabled(false);
44         Redo.setEnabled(false);
45         
46         add(New);
47         add(Open);
48         add(Save);
49         add(Build);
50         add(Run);
51         add(Undo);
52         add(Redo);
53         // 设置不可浮动
54         setFloatable(false);
55     }
56 
57     public static void main(String[] args) {
58         JFrame frame=new JFrame();
59         JTextArea text=new JTextArea();
60         frame.setLayout(new BorderLayout());
61         ToolBar bar=new ToolBar();
62         frame.add("Center",text);
63         frame.add("North",bar);
64         frame.setSize(400, 300);
65         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
66         frame.setVisible(true);
67         
68     }
69     
70     // 自定义button(带图片的和带提示的构造方法)
71     public class FgButton extends JButton {
72         public FgButton() {
73             super();
74         }
75 
76         public FgButton(Icon icon) {
77             super(icon);
78         }
79 
80         public FgButton(Icon icon, String strToolTipText) {
81             super(icon);
82             setToolTipText(strToolTipText);
83         }
84 
85         public FgButton(String text) {
86             super(text);
87         }
88 
89         public FgButton(String text, Icon icon, String strToolTipText) {
90             super(text, icon);
91             setToolTipText(strToolTipText);
92         }
93     }
94 
95 }
JToolBar.java

tongxunlu包:
主要是通讯录的各个功能实现:包括增加、删除、查找、替换....这个没怎么仔细加工,总之很水的,代码有点乱.... 
 

 

  1 package tongxunlu;
  2 
  3 
  4 import java.awt.Container;
  5 import java.awt.event.ActionEvent;
  6 import java.awt.event.ActionListener;
  7 import java.io.BufferedReader;
  8 import java.io.File;
  9 import java.io.FileNotFoundException;
 10 import java.io.FileReader;
 11 import java.io.FileWriter;
 12 import java.io.IOException;
 13 import java.io.PrintWriter;
 14 
 15 import javax.swing.JFrame;
 16 import javax.swing.JMenuBar;
 17 import javax.swing.JMenu;
 18 import javax.swing.JMenuItem;
 19 import javax.swing.JPanel;
 20 
 21 public class MyAddBook {
 22     public  JFrame frame;
 23     public  String Name;//文件保存名和路径
 24     public  String Path;
 25     
 26     public  void changeRoad(String path,String name){//更改路径函数
 27         
 28         //file2.renameTo(new File(path+name));
 29         try {//更新文件路径    
 30             FileWriter file1 = new FileWriter(path+name, true);
 31             PrintWriter write = new PrintWriter(file1);
 32             FileReader file2 = new FileReader(Path+Name);
 33             BufferedReader read = new BufferedReader(file2);
 34             String str;
 35             while((str=read.readLine())!=null){
 36                 write.println(str);
 37             }
 38             write.close();
 39             file1.close();
 40             read.close();
 41             file2.close();
 42             new File(Path+Name).delete();
 43         } catch (IOException e) {
 44             e.printStackTrace();
 45         }
 46         Name=name;Path=path;
 47         try {//保存文件路径
 48             new File("D://TXLData.txt").delete();//删除上次的
 49             FileWriter file1 = new FileWriter("D://TXLData.txt", true);
 50             PrintWriter write = new PrintWriter(file1);
 51             write.println(Path);
 52             write.println(Name);
 53             write.close();
 54             file1.close();
 55         } catch (IOException e) {
 56             // TODO Auto-generated catch block
 57             e.printStackTrace();
 58         }
 59     }
 60     private void Init(){//初始化路径
 61         try {
 62             BufferedReader read = new BufferedReader(new FileReader("D://TXLData.txt"));
 63             FileWriter file1 = new FileWriter("D://TEMP.txt", true);
 64             PrintWriter write = new PrintWriter(file1);
 65             String str;int ok=0;
 66             while((str=read.readLine())!=null){
 67                 Path=str;
 68                 Name=read.readLine();
 69                 ok=1;
 70             }
 71             if(ok==0){
 72                 Path="D:\\\\";
 73                 Name="TongXunLu.txt";
 74                 write.println(Path);
 75                 write.println(Name);
 76             }
 77             read.close();
 78             write.close();
 79             file1.close();
 80             new File("D://TXLData.txt").delete();
 81             File file2 = new File("D://TEMP.txt");
 82             file2.renameTo(new File("D://TXLData.txt"));
 83         }catch(FileNotFoundException e1){
 84         }catch (IOException e1) {}
 85     }
 86     public MyAddBook(){
 87         Init();
 88         frame = new JFrame("TAO~TAO通讯录");//主窗口
 89         
 90         JMenuBar menubar = new JMenuBar();
 91         
 92         JMenu edit = new JMenu("编辑");
 93         JMenuItem edit1 = new JMenuItem("录入");
 94         JMenuItem edit2 = new JMenuItem("查询");
 95         JMenuItem edit3 = new JMenuItem("删除");
 96         JMenuItem edit4 = new JMenuItem("修改");
 97         JMenuItem edit5 = new JMenuItem("排序");
 98         edit1.addActionListener(new Typein(Path,Name));
 99         JMenu show = new JMenu("显示信息");
100         JMenuItem show1 = new JMenuItem("classmates");
101         JMenuItem show2 = new JMenuItem("colleagues");
102         JMenuItem show3 = new JMenuItem("friends");
103         JMenuItem show4 = new JMenuItem("relatives");
104         JMenuItem show5 = new JMenuItem("all members");
105         Container c = frame.getContentPane();
106         JPanel pane = new JPanel();
107         c.add(pane);
108         pane.add(menubar);
109         menubar.add(edit);
110         edit.add(edit1);
111         edit.add(edit2);
112         edit.add(edit3);
113         edit.add(edit4);
114         edit.add(edit5);
115         menubar.add(show);
116         show.add(show1);
117         show.add(show2);
118         show.add(show3);
119         show.add(show4);
120         show.add(show5);
121         frame.setSize(300, 100);
122         
123         edit2.addActionListener(new ActionListener() // 监听查询
124         {
125             public void actionPerformed(ActionEvent e) {
126                 new Search(frame,"查询", 2,Path,Name).dialog.setVisible(true);
127             }
128         });
129         edit3.addActionListener(new ActionListener() // 监听删除
130         {
131             public void actionPerformed(ActionEvent e) {
132                 new Search(frame,"删除", 3,Path,Name).dialog.setVisible(true);
133             }
134         });
135         edit4.addActionListener(new ActionListener() // 监听修改
136         {
137             public void actionPerformed(ActionEvent e) {
138                 new Search(frame,"修改", 4,Path,Name).dialog.setVisible(true);
139             }
140         });
141         edit5.addActionListener(new ActionListener() // 监听排序
142         {
143             public void actionPerformed(ActionEvent e) {
144                 new Print("按姓名排序后", 2,Path,Name);
145             }
146         });
147         //------------------------------------------------------------
148         show1.addActionListener(new ActionListener() // 监听同学
149         {
150             public void actionPerformed(ActionEvent e) {
151                 new Print("classmates", 1,Path,Name);
152             }
153         });
154         show2.addActionListener(new ActionListener() // 监听同事
155         {
156             public void actionPerformed(ActionEvent e) {
157                 new Print("colleagues", 1,Path,Name);
158             }
159         });
160         show3.addActionListener(new ActionListener() // 监听朋友
161         {
162             public void actionPerformed(ActionEvent e) {
163                 new Print("friends", 1,Path,Name);
164             }
165         });
166         show4.addActionListener(new ActionListener() // 监听亲戚
167         {
168             public void actionPerformed(ActionEvent e) {
169                 new Print("relatives", 1,Path,Name);
170             }
171         });
172         show5.addActionListener(new ActionListener() // 监听全体人员
173         {
174             public void actionPerformed(ActionEvent e) {
175                 new Print("all members", 0,Path,Name);
176             }
177         });
178     }
179     public static void main(String[] args) {
180         
181     }
182 }
MyAddBook.java
 1 package tongxunlu;
 2 
 3 public class people {
 4 //"序号"//"姓名","性别","家庭住址","工作单位","邮政编码","家庭电话号码","办公室电话号码","传真号码","移动电话号码","Email","QQ","MSN","出生日期","备注"
 5     
 6     public  String People[]=new String[16];
 7     public people(String args){
 8         //把args转成people
 9         String temp="";char c;
10         for(int i=0,j=1;i<args.length();i++){
11             c=args.charAt(i);
12             if(c!='|'){
13                 temp+=c;
14             }else{
15                 People[j]=new String(temp);
16                 temp="";
17                 j++;
18             }
19         }
20     }
21     public static String findName(String args){//查找人命
22         String temp="";char c;
23         for(int i=0,j=1;i<args.length();i++){
24             c=args.charAt(i);
25             if(c!='|'){
26                 temp+=c;
27             }else{
28                 break;
29             }
30         }
31         return temp;
32     }
33 }
people.java
  1 package tongxunlu;
  2 
  3 import java.awt.Dimension;
  4 import java.io.BufferedReader;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileReader;
  7 import java.io.IOException;
  8 import java.text.Collator;
  9 import java.util.Arrays;
 10 import java.util.Comparator;
 11 import java.util.Vector;
 12 
 13 import javax.swing.JFrame;
 14 import javax.swing.JScrollPane;
 15 import javax.swing.JTable;
 16 import javax.swing.table.DefaultTableModel;
 17 
 18 // 输出类
 19 public class Print {
 20     
 21     String[] firstList = new String[]{"序号","姓名","性别","家庭住址","工作单位","邮政编码","家庭电话号码","办公室电话号码","传真号码","移动电话号码","Email","QQ","MSN","出生日期","关系","备注"};
 22     DefaultTableModel m_data;
 23     JTable m_view;
 24     people people1;
 25     public String Name,Path;//文件保存名和路径
 26     
 27     public Print(String st, int n,String path,String name){
 28         Name=name;Path=path;
 29         JFrame frame = new JFrame(st + "信息如下");
 30         frame.setSize(800, 400);
 31         // frame.setLocation(350, 150);
 32         m_data = new DefaultTableModel(null,mb_getColumnNames(firstList)); // 创建一个空的数据表格
 33         m_view = new JTable(m_data);
 34         m_view.setPreferredScrollableViewportSize(new Dimension(800,400)); // 设置表格的显示区域大小
 35         m_view.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
 36         m_view.setEnabled(false);//设置不可编辑
 37         JScrollPane sPane = new JScrollPane(m_view);
 38         frame.add(sPane);
 39         frame.setVisible(true);
 40         if (n == 3){//查找某人
 41             try {
 42                 BufferedReader read = new BufferedReader(new FileReader(Path+Name));        
 43                 int z = 1;
 44                 while (z == 1) {
 45                     String str = read.readLine();
 46                     if (str != null){    
 47                         people1=new people(str);
 48                         if(people1.People[1].equals(st)){
 49                             people1.People[0]=new String(Integer.toString(m_data.getRowCount()+1));
 50                             m_data.addRow(mb_getColumnNames(people1.People));
 51                         }    
 52                     }else z = 0;    
 53                 }
 54                 read.close();
 55             } catch (FileNotFoundException e1) {    
 56             } catch (IOException e2) {}
 57         }
 58         
 59         if (n == 2){// 排序
 60             try{ 
 61                 int i;
 62                 String[] all;
 63                 all = new String[10000];
 64                 BufferedReader read = new BufferedReader(new FileReader(Path+Name));
 65                 
 66                 int z = 1,count = 0;
 67                 while (z == 1) {
 68                     for (i=0; i<10000;i++){
 69                         String str=read.readLine();
 70                         if(str!=null){
 71                             all[i] = str;
 72                             count++;
 73                         }else z=0;                        
 74                     }
 75                 }
 76                 String[] bll = new String[count];
 77                 for (i = 0; i < count; i++)
 78                     bll[i] = all[i];
 79                 getSortOfChinese(bll);
 80                 for (i = 0; i < count; i++){
 81                     people1=new people(bll[i]);
 82                     people1.People[0]=new String(Integer.toString(i+1));
 83                     m_data.addRow(mb_getColumnNames(people1.People));
 84                 }
 85                 read.close();
 86             } catch (FileNotFoundException e1) {
 87             } catch (IOException e2) {}
 88         }
 89             
 90             
 91         if (n == 1){// 各类人员
 92             try {
 93                 BufferedReader read = new BufferedReader(new FileReader(Path+Name));        
 94                 int z = 1;
 95                 while (z == 1) {
 96                     String str = read.readLine();
 97                     if (str != null){    
 98                         people1=new people(str);
 99                         if(people1.People[14].equals(st)){
100                             people1.People[0]=new String(Integer.toString(m_data.getRowCount()+1));
101                             m_data.addRow(mb_getColumnNames(people1.People));
102                         }    
103                     }else z = 0;    
104                 }
105                 read.close();
106             } catch (FileNotFoundException e1) {    
107             } catch (IOException e2) {}
108         }
109 
110         if(n == 0){// 全体人员信息
111             try {
112                 BufferedReader read = new BufferedReader(new FileReader(Path+Name));        
113                 int z = 1;
114                 while (z == 1) {
115                     String str = read.readLine();
116                     if (str != null){    
117                         //System.out.print(Integer.toString(m_data.getRowCount()+1));
118                         people1=new people(str);
119                         people1.People[0]=new String(Integer.toString(m_data.getRowCount()+1));
120                         m_data.addRow(mb_getColumnNames(people1.People));
121                     }
122                     else
123                         z = 0;
124                 }
125                 read.close();
126             } catch (FileNotFoundException e1) {    
127             } catch (IOException e2) {}
128         }
129     }
130     
131     public Vector<String> mb_getColumnNames(String args[]) // 数组转向量
132     {
133         Vector<String> vs = new Vector<String>();
134         for (int i = 0; i <args.length; i++)
135             vs.add(args[i]);
136         return (vs);
137     } // 方法mb_getColumnNames结束
138     
139     @SuppressWarnings("unchecked")
140     public static String[] getSortOfChinese(String[] a) {
141         // Collator 类是用来执行区分语言环境这里使用CHINA
142         Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
143 
144         // JDKz自带对数组进行排序。
145         Arrays.sort(a, cmp);
146         return a;
147     }
148 }
Print.java
  1 package tongxunlu;
  2 
  3 import java.awt.Container;
  4 import java.awt.GridLayout;
  5 import java.awt.event.ActionEvent;
  6 import java.awt.event.ActionListener;
  7 import java.io.BufferedReader;
  8 import java.io.File;
  9 import java.io.FileNotFoundException;
 10 import java.io.FileReader;
 11 import java.io.FileWriter;
 12 import java.io.IOException;
 13 import java.io.PrintWriter;
 14 import javax.swing.JButton;
 15 import javax.swing.JDialog;
 16 import javax.swing.JFrame;
 17 import javax.swing.JLabel;
 18 import javax.swing.JOptionPane;
 19 import javax.swing.JPanel;
 20 import javax.swing.JTextField;
 21 
 22 //查询修改删除
 23 public class Search {
 24     
 25     public JDialog dialog;
 26     public String Name,Path;//文件保存名和路径
 27     public Search(final JFrame frame,String str, int n,String path,String name) {
 28         Path=path;Name=name;
 29         dialog= new JDialog(frame, "查询对话框", true);
 30         dialog.setSize(250, 200);
 31         Container c = dialog.getContentPane();
 32         dialog.setLayout(new GridLayout(2, 1, 5, 5));
 33         JLabel Lsearch = new JLabel("请输入要" + str + "人员的名字:");
 34         final JTextField Tname = new JTextField(10);
 35         JButton certain = new JButton("确定");
 36         JButton cancel = new JButton("取消");
 37         // final String in=Tname.getText();
 38         JPanel pane1 = new JPanel();
 39         JPanel pane2 = new JPanel();
 40         c.add(pane1);
 41         c.add(pane2);
 42         pane1.add(Lsearch);
 43         pane1.add(Tname);
 44         pane2.add(certain);
 45         pane2.add(cancel);
 46         dialog.setDefaultCloseOperation(dialog.DISPOSE_ON_CLOSE);
 47         if (n == 2) {// 查询
 48             certain.addActionListener(new ActionListener() 
 49             {
 50                 public void actionPerformed(ActionEvent e){
 51                     if(Tname.getText()=="")
 52                         JOptionPane.showMessageDialog(dialog,"请输入内容","警告",JOptionPane.WARNING_MESSAGE);
 53                     else{
 54                         dialog.dispose();//problem appearent
 55                         new Print(Tname.getText(),3,Path,Name);
 56                     }
 57                 }
 58             });
 59         }
 60         if(n==3) {
 61             certain.addActionListener(new ActionListener() // 删除
 62             {
 63                 public void actionPerformed(ActionEvent e) {
 64                     try {
 65                         BufferedReader read = new BufferedReader(new FileReader(Path+Name));
 66                         FileWriter file1 = new FileWriter("D://TEMP.txt", true);
 67                         PrintWriter write = new PrintWriter(file1);
 68                         int z = 1,ok=0;
 69                         while (z==1) {
 70                             String str=read.readLine();
 71                             if (str!= null){    
 72                                 String s = people.findName(str);
 73                                 if (!(s.equals(Tname.getText()))) {
 74                                     write.println(str);
 75                                 }else{
 76                                     ok=1;//标记是否有被删除对象
 77                                 }
 78                             }else z = 0;    
 79                         }
 80                         // file.close();
 81                         read.close();
 82                         write.close();
 83                         file1.close();
 84                         new File(Path+Name).delete();
 85                         //System.out.println(Path+" "+Name);
 86                         File file2 = new File("D://TEMP.txt");
 87                         file2.renameTo(new File(Path+Name));
 88                         if(ok==1)JOptionPane.showMessageDialog(null,Tname.getText()+"被成功删除", "删除结果",JOptionPane.INFORMATION_MESSAGE);
 89                         else JOptionPane.showMessageDialog(null,"未找到"+Tname.getText(), "删除结果",JOptionPane.WARNING_MESSAGE);
 90                     } catch (FileNotFoundException e1) {
 91                         // TODO Auto-generated catch block
 92                         // e1.printStackTrace();
 93                         JOptionPane.showMessageDialog(null, "未找到文件");
 94                     } catch (IOException e2) {
 95                         // TODO Auto-generated catch block
 96                         // e2.printStackTrace();
 97                         System.out.print("未找到该人员");
 98                     }
 99                 }
100             });
101         }
102         if(n == 4){
103             certain.addActionListener(new ActionListener() // 修改
104             {
105                 public void actionPerformed(ActionEvent e) {    
106                         try {
107                             BufferedReader read = new BufferedReader(new FileReader(Path+Name));
108                             FileWriter file1 = new FileWriter("D://TEMP.txt", true);
109                             PrintWriter write = new PrintWriter(file1);
110                             int z = 1,ok=0;
111                             while (z==1){
112                                 String str=read.readLine();
113                                 if (str!= null){    
114                                     String s = people.findName(str);
115                                     if (!(s.equals(Tname.getText()))) {
116                                         write.println(str);
117                                     }else{
118                                         //dialog.dispose();
119                                         Typein a=new Typein(frame,str,write,Path,Name);
120                                         a.typein();
121                                         ok=1;//标记是否有这个人,0有
122                                         //System.out.print(1);
123                                         //a.frame.dispose();
124                                     }
125                                 }else z=0;
126                             }
127                             // file.close();
128                             read.close();
129                             write.close();
130                             file1.close();
131                             new File(Path+Name).delete();
132                             File file2 = new File("D://TEMP.txt");
133                             file2.renameTo(new File(Path+Name));
134                             if(ok==1)JOptionPane.showMessageDialog(null,Tname.getText()+"被成功修改", "修改结果",JOptionPane.INFORMATION_MESSAGE);
135                             else JOptionPane.showMessageDialog(null,"未找到"+Tname.getText(), "修改结果",JOptionPane.WARNING_MESSAGE);
136                         }catch(FileNotFoundException e1){
137                         }catch (IOException e1) {}
138                     }
139                 });                
140         }
141             
142                         
143                             
144                     
145                     /*            if (Typein.z == 1) {
146                                     write.print(Tname.getText() + '\t');
147                                     write.print(s1 + '\t');
148                                     write.print(s2 + ' ');
149                                     write.print(s3 + ' ');
150                                     write.print(s4 + '\t');
151                                     write.print(s5 + '\t');
152                                     write.print(s6 + '\t');
153                                     write.println(s7);
154                                     Typein.z = 2;
155 
156                                 }
157                             }
158                         }
159                         
160 
161                     } catch (FileNotFoundException e1) {
162                         // TODO Auto-generated catch block
163                         // e1.printStackTrace();
164                         System.out.print("未找到文件");
165                     } catch (IOException e2) {
166                         // TODO Auto-generated catch block
167                         // e2.printStackTrace();
168                         System.out.print("未找到该人员");
169                     }
170                 }
171             });
172         }*/
173         cancel.addActionListener(new ActionListener() // 取消
174         {
175             public void actionPerformed(ActionEvent e) {
176                   dialog.dispose();
177             }
178         });
179     }
180 }
Search.java
  1 package tongxunlu;
  2 
  3 import java.awt.Choice;
  4 import java.awt.Container;
  5 import java.awt.Font;
  6 import java.awt.GridLayout;
  7 import java.awt.event.ActionEvent;
  8 import java.awt.event.ActionListener;
  9 import java.io.FileWriter;
 10 import java.io.IOException;
 11 import java.io.PrintWriter;
 12 
 13 import javax.swing.JButton;
 14 import javax.swing.JDialog;
 15 import javax.swing.JFrame;
 16 import javax.swing.JLabel;
 17 import javax.swing.JOptionPane;
 18 import javax.swing.JPanel;
 19 import javax.swing.JTextField;
 20 import javax.swing.table.DefaultTableModel;
 21 
 22 //输入类
 23 public class Typein implements ActionListener {
 24     String[] firstList = new String[]{"姓名*","性别","家庭住址","工作单位","邮政编码","家庭电话号码","办公室电话号码","传真号码","移动电话号码","Email","QQ","MSN","出生日期","关系","备注"};
 25     public static int z = 2;
 26     public static int y = 0;
 27     public JLabel[] label=new JLabel[15];//15个label
 28     public JTextField[] textfield=new JTextField[12];//12个文本编辑区
 29     public Choice Cgroup = new Choice(),Cfimle = new Choice(), Cbirthyear = new Choice(),//5个选择组(单选)
 30             Cbirthmonth = new Choice(), Cbirthday = new Choice();
 31     public JButton certain1, cancel;//2个按钮
 32     public JDialog frame;//主界面
 33     public String Include="";
 34     private PrintWriter write;
 35     public String Name,Path;//文件保存名和路径
 36     public Typein(String path,String name) {//1遍
 37         Name=name;Path=path;//路径
 38         frame=new JDialog();
 39         frame.setTitle("查找界面");
 40         Cgroup.addItem("null");//把单选按钮组组好
 41         Cgroup.addItem("classmates");
 42         Cgroup.addItem("colleagues");
 43         Cgroup.addItem("friends");
 44         Cgroup.addItem("relatives");
 45         Cfimle.addItem("nan");
 46         Cfimle.addItem("nv");
 47         Cbirthyear.addItem("1985");
 48         Cbirthyear.addItem("1986");
 49         Cbirthyear.addItem("1987");
 50         Cbirthyear.addItem("1988");
 51         Cbirthyear.addItem("1989");
 52         Cbirthyear.addItem("1990");
 53         Cbirthyear.addItem("1991");
 54         Cbirthyear.addItem("1992");
 55         Cbirthyear.addItem("1993");
 56         Cbirthyear.addItem("1994");
 57         Cbirthyear.addItem("1995");
 58         Cbirthyear.addItem("1996");
 59         Cbirthyear.addItem("1997");
 60         Cbirthyear.addItem("1998");
 61         Cbirthyear.addItem("1999");
 62         Cbirthyear.addItem("2000");
 63         Cbirthmonth.addItem("01");
 64         Cbirthmonth.addItem("02");
 65         Cbirthmonth.addItem("03");
 66         Cbirthmonth.addItem("04");
 67         Cbirthmonth.addItem("05");
 68         Cbirthmonth.addItem("06");
 69         Cbirthmonth.addItem("07");
 70         Cbirthmonth.addItem("08");
 71         Cbirthmonth.addItem("09");
 72         Cbirthmonth.addItem("10");
 73         Cbirthmonth.addItem("11");
 74         Cbirthmonth.addItem("12");
 75         Cbirthday.addItem("01");
 76         Cbirthday.addItem("02");
 77         Cbirthday.addItem("03");
 78         Cbirthday.addItem("04");
 79         Cbirthday.addItem("05");
 80         Cbirthday.addItem("06");
 81         Cbirthday.addItem("07");
 82         Cbirthday.addItem("08");
 83         Cbirthday.addItem("09");
 84         Cbirthday.addItem("10");
 85         Cbirthday.addItem("11");
 86         Cbirthday.addItem("12");
 87         Cbirthday.addItem("13");
 88         Cbirthday.addItem("14");
 89         Cbirthday.addItem("15");
 90         Cbirthday.addItem("16");
 91         Cbirthday.addItem("17");
 92         Cbirthday.addItem("18");
 93         Cbirthday.addItem("19");
 94         Cbirthday.addItem("20");
 95         Cbirthday.addItem("21");
 96         Cbirthday.addItem("22");
 97         Cbirthday.addItem("23");
 98         Cbirthday.addItem("24");
 99         Cbirthday.addItem("25");
100         Cbirthday.addItem("26");
101         Cbirthday.addItem("27");
102         Cbirthday.addItem("28");
103         Cbirthday.addItem("29");
104         Cbirthday.addItem("30");
105         Cbirthday.addItem("31");
106     }
107 
108     public Typein(JFrame jframe,String include,PrintWriter printwriter,String path,String name) {//含参构造函数(内容)
109         frame=new JDialog(jframe,"修改界面",true);
110         Include=include;write=printwriter;
111         Name=name;Path=path;//路径
112         Cgroup.addItem("null");//把单选按钮组组好
113         Cgroup.addItem("classmates");
114         Cgroup.addItem("colleagues");
115         Cgroup.addItem("friends");
116         Cgroup.addItem("relatives");
117         Cfimle.addItem("nan");
118         Cfimle.addItem("nv");
119         Cbirthyear.addItem("1985");
120         Cbirthyear.addItem("1986");
121         Cbirthyear.addItem("1987");
122         Cbirthyear.addItem("1988");
123         Cbirthyear.addItem("1989");
124         Cbirthyear.addItem("1990");
125         Cbirthyear.addItem("1991");
126         Cbirthyear.addItem("1992");
127         Cbirthyear.addItem("1993");
128         Cbirthyear.addItem("1994");
129         Cbirthyear.addItem("1995");
130         Cbirthyear.addItem("1996");
131         Cbirthyear.addItem("1997");
132         Cbirthyear.addItem("1998");
133         Cbirthyear.addItem("1999");
134         Cbirthyear.addItem("2000");
135         Cbirthmonth.addItem("01");
136         Cbirthmonth.addItem("02");
137         Cbirthmonth.addItem("03");
138         Cbirthmonth.addItem("04");
139         Cbirthmonth.addItem("05");
140         Cbirthmonth.addItem("06");
141         Cbirthmonth.addItem("07");
142         Cbirthmonth.addItem("08");
143         Cbirthmonth.addItem("09");
144         Cbirthmonth.addItem("10");
145         Cbirthmonth.addItem("11");
146         Cbirthmonth.addItem("12");
147         Cbirthday.addItem("01");
148         Cbirthday.addItem("02");
149         Cbirthday.addItem("03");
150         Cbirthday.addItem("04");
151         Cbirthday.addItem("05");
152         Cbirthday.addItem("06");
153         Cbirthday.addItem("07");
154         Cbirthday.addItem("08");
155         Cbirthday.addItem("09");
156         Cbirthday.addItem("10");
157         Cbirthday.addItem("11");
158         Cbirthday.addItem("12");
159         Cbirthday.addItem("13");
160         Cbirthday.addItem("14");
161         Cbirthday.addItem("15");
162         Cbirthday.addItem("16");
163         Cbirthday.addItem("17");
164         Cbirthday.addItem("18");
165         Cbirthday.addItem("19");
166         Cbirthday.addItem("20");
167         Cbirthday.addItem("21");
168         Cbirthday.addItem("22");
169         Cbirthday.addItem("23");
170         Cbirthday.addItem("24");
171         Cbirthday.addItem("25");
172         Cbirthday.addItem("26");
173         Cbirthday.addItem("27");
174         Cbirthday.addItem("28");
175         Cbirthday.addItem("29");
176         Cbirthday.addItem("30");
177         Cbirthday.addItem("31");
178     }
179     
180     public void typein() {//多遍
181         Container c = frame.getContentPane();
182         frame.setSize(500,300);
183         frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
184         frame.setResizable(false);
185         frame.setLayout(new GridLayout(8,2, 5, 5));
186         
187         for(int i=0;i<firstList.length;i++){
188             label[i]=new JLabel(firstList[i]);
189             //label[i].setFont(new Font("微软雅黑",0,12));
190         }
191         
192         if(Include=="")for(int i=0;i<textfield.length;i++){
193             textfield[i]=new JTextField(10);
194         }else{
195             people Peo=new people(Include);
196             /*for(int i=1;i<Peo.People.length;i++){
197                 System.out.println(i+Peo.People[i]);
198             }*/
199             for(int i=0,j=1;j<Peo.People.length;j++){
200                 if(j==2||j==13||j==14)continue;
201                 else{
202                     textfield[i]=new JTextField(10);
203                     textfield[i].setText(Peo.People[j]);
204                     i++;
205                 }
206                 
207             }
208         }
209         
210         certain1 = new JButton("确定");
211         cancel = new JButton("取消");
212         
213         JPanel[] panel = new JPanel[16];
214         for(int i=0;i<panel.length;i++){
215             panel[i]=new JPanel();
216             panel[i].setLayout(new GridLayout(1,2));
217             c.add(panel[i]);
218         }
219         
220         for(int i=0,j=0;i<panel.length-1;i++){
221             if(i==1){
222                 panel[i].add(label[i]);
223                 panel[i].add(Cfimle);
224             }else if(i==12){
225                 panel[i].add(label[i]);
226                 panel[i].add(Cbirthyear);
227                 panel[i].add(Cbirthmonth);
228                 panel[i].add(Cbirthday);
229             }else if(i==13){
230                 panel[i].add(label[i]);
231                 panel[i].add(Cgroup);
232             }else{
233                 panel[i].add(label[i]);
234                 panel[i].add(textfield[j++]);
235             }        
236         }
237         if(Include!=""){//包含内容对选择框初始化
238             people Peo=new people(Include);
239             Cfimle.select(Peo.People[2]);
240             Cbirthyear.select(Peo.People[13].substring(0,4));
241             Cbirthmonth.select(Peo.People[13].substring(5,7));
242             Cbirthday.select(Peo.People[13].substring(8,10));
243             Cgroup.select(Peo.People[14]);
244         }
245         
246         panel[15].add(certain1);
247         panel[15].add(cancel);
248                 
249         certain1.addActionListener(new ActionListener() // 设置监听器
250         {
251             public void actionPerformed(ActionEvent e) // 用匿名内部类实现监听器
252             {
253                 
254                 if (textfield[0].getText().equals(""))
255                     JOptionPane.showMessageDialog(null, "录入失败,姓名必须填写!", "录入结果",
256                             JOptionPane.INFORMATION_MESSAGE);
257                 else {
258                     try {
259                         String s="";
260                         for(int i=0,j=0;i<label.length;i++){
261                             if(i==1){
262                                 s+=(Cfimle.getSelectedItem()+"|");
263                             }else if(i==12){
264                                 s+=(Cbirthyear.getSelectedItem()+'-'+Cbirthmonth.getSelectedItem()+'-'+Cbirthday.getSelectedItem()+"|");
265                             }else if(i==13){
266                                 s+=(Cgroup.getSelectedItem()+"|");
267                             }else{
268                                 if(textfield[j].getText().equals(""))s+=("null|");
269                                 else s+=(textfield[j].getText()+"|");
270                                 j++;
271                             }    
272                         }//获取窗口数据转换成待存入的一行数据
273                         if(Include==""){
274                             FileWriter AddressBook = new FileWriter(Path+Name, true);
275                             PrintWriter add = new PrintWriter(AddressBook);
276                             add.println(s);
277                             add.close();
278                             AddressBook.close();
279                             z = 1;
280                             System.out.println(897);
281                         }else{
282                             //System.out.println(s);
283                             write.println(s);
284                             //write.close();
285                             z=2;
286                             y=1;
287                         }
288                     } catch (IOException e1) {}
289                     if (y == 0) {
290                         JOptionPane.showMessageDialog(null, "录入成功", "录入结果",
291                                 JOptionPane.INFORMATION_MESSAGE);
292                     } else {
293                         frame.dispose();
294                         z = 0;
295                     }
296                     
297                     for(int i=0,j=0;i<label.length;i++){
298                         if(i==1){
299                             Cfimle.select(0);
300                         }else if(i==12){
301                             Cbirthyear.select(0);
302                             Cbirthmonth.select(0);
303                             Cbirthday.select(0);
304                         }else if(i==13){
305                             Cgroup.select(0);
306                         }else{
307                             textfield[j].setText("");
308                             j++;
309                         }
310                         Include="";
311                     }
312                 }
313             }
314         });
315         cancel.addActionListener(new ActionListener() // 设置监听器
316         {
317             public void actionPerformed(ActionEvent e) // 用匿名内部类实现监听器
318             {
319                 frame.dispose();
320                 z = 0;
321             }
322         });
323         frame.setVisible(true);
324     }
325     public void actionPerformed(ActionEvent e) {
326         new Typein(Path,Name).typein();
327     }
328     public static void main(String afd[]) throws IOException{
329         JFrame frame=new JFrame();
330         FileWriter file1 = new FileWriter("D:\\AddressBook.txt", true);
331         PrintWriter write = new PrintWriter(file1);
332         Typein a=new Typein(frame,"李涛|nan|安徽|zjut|123456|888888888|23423423|3242342342|32423423423423|953521476@qq.com|953521476|fasjosafj|1985-01-01|classmates|ta0|",write,"D:\\","AddressBook.txt");
333         a.typein();
334         //new Typein().typein();
335     }
336 }
Typein.java

BianYi包:
Commond类:主要负责调用DOS窗口,进行编译、运行java文件,同时向DOS内读写数据,包括错误流。更多介绍请看代码(可以直接运行):

  1 package BianYi;
  2 
  3 import java.awt.event.WindowEvent;
  4 import java.awt.event.WindowListener;
  5 import java.io.*;
  6 import java.text.SimpleDateFormat;
  7 import java.util.Date;
  8 import javax.swing.JDialog;
  9 import javax.swing.JFrame;
 10 import javax.swing.JScrollPane;
 11 import javax.swing.JTextArea;
 12 
 13 public class Commond{
 14     public static ResultShow show;
 15     
 16     //构造函数,显示窗口大小和位置
 17     public Commond(int sX,int sY,int pX,int pY){
 18         show=new ResultShow(sX,sY,pX,pY);
 19     }
 20     
 21     //输入文件名,路径,是调试还是运行0-1,返回编译结果String
 22     public String getInfoDOS(String name,String path,boolean TranslateOrRun) throws IOException, InterruptedException{
 23         String result="",temp="",in;
 24         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
 25         if(!TranslateOrRun){
 26             in="cmd /c javac "+name;
 27             result+="*********************************************************************************************************************\n";
 28             result+="                                           ! Tao-Tao: "+df.format(new Date())+"  "+"编译: "+path+name+" ^_^!\n";
 29             result+="*********************************************************************************************************************\n";
 30         }
 31         else{
 32             String preName=name.substring(0,name.lastIndexOf('.'));
 33             in="cmd /c java "+preName;
 34             result+="*********************************************************************************************************************\n";
 35             result+="                                           ! Tao-Tao: "+df.format(new Date())+"  "+"运行: "+path+name+" ^_^!\n";
 36             result+="*********************************************************************************************************************\n";
 37         }
 38         Process process = Runtime.getRuntime().exec(in,null,new File(path));
 39         
 40         int beginStrLength=result.length();
 41         BufferedReader bufferedReaderErro = new BufferedReader(new InputStreamReader(process.getErrorStream()));
 42         while ((temp=bufferedReaderErro.readLine()) != null) 
 43             result+=(temp+'\n');
 44         BufferedReader bufferedReaderCorr = new BufferedReader(new InputStreamReader(process.getInputStream()));
 45         while ((temp=bufferedReaderCorr.readLine()) != null) 
 46             result+=(temp+'\n');
 47         int endStrLength=result.length();
 48         
 49         process.waitFor(); 
 50         
 51         if(beginStrLength==endStrLength)result+="success!\n";
 52         //JOptionPane.showConfirmDialog(null,result,"结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
 53         return result;    
 54     }
 55     
 56     //内部类,显示窗口
 57     public class ResultShow implements WindowListener{
 58         public JTextArea text;//文本显示区
 59         public JDialog Dialog;//面板
 60         
 61         //构造函数窗口大小和位置
 62         public ResultShow(int sX,int sY,int pX,int pY){
 63             text=new JTextArea();
 64             text.setLineWrap(false);//自动换行
 65             text.setWrapStyleWord(false);//自动换行换单词
 66             text.setEditable(false);
 67             Dialog=new JDialog();
 68             JScrollPane sp=new JScrollPane(text);//添加带滚动条(JScrollPane)的文本编辑框JTextArea
 69             Dialog.add(sp);
 70             Dialog.setSize(sX,sY);
 71             Dialog.setLocation(pX,pY);
 72             Dialog.setResizable(false);//大小不可变
 73             Dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//关闭
 74             Dialog.addWindowListener(this);//窗口监听%%%%%%%
 75         }
 76         
 77         //导入结果并显示
 78         public void addStr(String result){
 79             //text.setText(result);
 80             text.append(result);
 81             Dialog.setVisible(true);
 82         }
 83         
 84         //重定义窗口关闭
 85         public void windowClosing(WindowEvent e) {
 86             Dialog.setVisible(false);    
 87         }
 88         public void windowOpened(WindowEvent e) {}
 89         public void windowClosed(WindowEvent e) {}
 90         public void windowIconified(WindowEvent e) {}
 91         public void windowDeiconified(WindowEvent e) {}
 92         public void windowActivated(WindowEvent e) {}
 93         public void windowDeactivated(WindowEvent e) {}
 94     }
 95     
 96     //main测试
 97     public static void main(String args[]) throws IOException, InterruptedException{
 98         Commond C=new Commond(600,400,100,100);
 99         String s=C.getInfoDOS("BB.java","D:\\",false);show.addStr(s);
100         s=C.getInfoDOS("BB.java","D:\\",true);show.addStr(s);
101     }
102 }
Commond.java

App包:
主要是一些简单的功能:如回文串判断、数字翻译成英文...没啥技术含量.....

 1 package App;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.io.RandomAccessFile;
 7 import java.util.Scanner;
 8 
 9 import javax.swing.JOptionPane;
10 
11 public class CountString{
12     private static String word[]=new String[10000];
13     private static int numWord;
14     
15     public static void main(String args[]) throws IOException{
16         CountString a=new CountString("D:/test.txt");
17     }
18     
19     public CountString(String path) throws IOException{
20         numWord=0;
21         Fread(path);
22         String s=new String(("|--以w开头的单词数量:   "+countBeginWith('w'))+
23                 ("\n|--含有or的单词数量:    "+countInclude("or"))+
24                 ("\n|--含有长为3的单词数量: "+countLength(3))
25         );
26         JOptionPane.showConfirmDialog(null,s,"回文数",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
27     }//构造函数
28     
29     private static void Fread(String path) throws IOException{
30         int c;String temp = "";
31         RandomAccessFile f=new RandomAccessFile(path,"r");
32         while((c=f.read()) !=-1){
33             if((char)c==' ' || (char)c=='\n'){
34                 if(temp!=""){//System.out.println(temp);
35                     if(isWord(temp)==0)    System.out.println(1);
36                     word[numWord++]=temp.toLowerCase();//else 
37                     temp="";
38                 }
39                 while((char)c==' ' || (char)c=='\n'){c=f.read();}
40             }
41             if(c==13)continue;//System.out.print("->"+(char)c+"("+c+")");
42             temp+=(char)c;
43         }
44         //for(int j=0;j<numWord;j++)System.out.println(word[j]);
45     }//读取文件成
46 
47     private static int isWord(String temp){
48         int len=temp.length();
49         for(int i=0;i<len;i++)
50             if(temp.charAt(i)<'A'||temp.charAt(i)>'z')
51                 return 0;
52         return 1;
53     }//判断输入是否是合法单词
54     
55     private static int countBeginWith(char c){
56         int count=0;
57         if(c>'z')c=(char)(c-('A'-'a'));
58         for(int i=0;i<numWord;i++)
59             if(word[i].charAt(0)==c)
60                 count++;
61         return count;
62     }//统计单词中以char c开头的数目(不分大小写)
63     
64     private static int countInclude(String c){
65         int count=0;
66         for(int i=0;i<numWord;i++)
67             if(word[i].indexOf(c)!=-1)
68                 count++;
69         return count;
70     }//统计单词中含有String c的单词数(不分大小写)
71     
72     private static int countLength(int c){
73         int count=0;
74         for(int i=0;i<numWord;i++)
75             if(word[i].length()==c)
76                 count++;
77         return count;
78     }//统计单词中长为c的数量
79 }
CountString.java
  1 package App;
  2 import javax.swing.JDialog;
  3 import javax.swing.JLabel;
  4 import javax.swing.JOptionPane;
  5 import javax.swing.JPanel;
  6 import javax.swing.JFrame;
  7 import javax.swing.JProgressBar;
  8 
  9 
 10 import java.awt.Color;
 11 import java.awt.Dimension;
 12 import java.awt.Toolkit;
 13 import java.awt.Window;
 14 import java.io.IOException;
 15 import java.io.RandomAccessFile;
 16 
 17 public class FQiuHe{
 18     static BarThread stepper;
 19     static JProgressBar aJProgressBar;
 20     String up=null,down=null;
 21     static JLabel Lup;
 22     static JLabel Ldown;
 23     //---
 24     static int sum=0;
 25     static double sumpross=0.0;
 26     public static String bianLiang[]=new String[20000];
 27     public static double shuZhi[]=new double[20000];
 28     //进度条线程
 29     static class BarThread extends Thread{
 30         private static int DELAY = 1;
 31         JProgressBar progressBar;
 32         //构造方法
 33         public BarThread(JProgressBar bar) {
 34             progressBar = bar;
 35         }
 36         //线程体
 37         public void run(){
 38             for(int i=0;i<sum;i++){
 39                 try {
 40                     if(sum-i-1<1000)Ldown.setText("正在计算......剩余 "+(sum-(i+1))+" ms");
 41                     else Ldown.setText("正在计算......剩余 "+(sum-(i+1))/1000+" s");
 42                     Thread.sleep(DELAY);
 43                     sumpross+=shuZhi[i];
 44                     Lup.setText("当前正在计算"+bianLiang[i]+"....."+(i+1)+"/"+sum+".....总和为: "+sumpross);
 45                     int value = progressBar.getValue();
 46                     progressBar.setValue(value +1);
 47                 } catch (InterruptedException e) {}
 48             }            
 49             Ldown.setText("计算完成!");
 50             int c;
 51             if((c=JOptionPane.showConfirmDialog(null,"总和为: "+sumpross,"计算结果",
 52                     JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE))==0 || c==1){
 53                 stepper.stop();
 54                 return;
 55             }
 56         }
 57     }
 58     public FQiuHe(String path,JFrame parent){//界面构造函数
 59         //if(Read(path)==false)
 60             //JOptionPane.showMessageDialog(null,"发现文件数据有误...","错误提醒",JOptionPane.WARNING_MESSAGE);
 61         //else{
 62             Read(path);
 63             JDialog frm= new JDialog(parent,"JFrame with JProgressBar",true);
 64             frm.setLayout(null);
 65             //frm.setFocusable(true);
 66             //frm.setAlwaysOnTop(true);
 67             //设置进度条属性
 68             aJProgressBar = new JProgressBar(0,sum);//进度条从0-sum
 69             aJProgressBar.setStringPainted(true);
 70             aJProgressBar.setBackground(Color.white);
 71             aJProgressBar.setForeground(Color.red);        
 72             aJProgressBar.setBounds(0,25, 600,110);
 73             frm.add(aJProgressBar);
 74             //2个label
 75             Lup=new JLabel("up");
 76             Lup.setBounds(0,0,600, 25);
 77             frm.add(Lup);
 78             Ldown=new JLabel(down);
 79             Ldown.setBounds(0,135,600,35);
 80             frm.add(Ldown);
 81             //设置窗口属性
 82             //frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 83             frm.setSize(600, 200);
 84             centerWindow(frm);
 85             frm.setResizable(false);
 86             stepper=new BarThread(aJProgressBar);
 87             stepper.start();
 88             frm.setVisible(true);
 89         //}
 90         
 91     }
 92     private void centerWindow(Window f) {//设置窗口居中
 93         Toolkit tk=f.getToolkit();//获得显示屏桌面窗口的大小
 94         Dimension dm=tk.getScreenSize();
 95         f.setLocation((int)(dm.getWidth()-f.getWidth())/2,(int)(dm.getHeight()-f.getHeight())/2);//让窗口居中显示    
 96     }
 97     static boolean Read(String path){//读取文件函数
 98         try{
 99             sum=0;
100             sumpross=0.0;
101             //RandomAccessFile f=new RandomAccessFile(args[0],"r");
102             RandomAccessFile f=new RandomAccessFile(path,"rw");
103             String s,temp;
104             while((s=f.readLine())!=null){
105                 s=s.trim();
106                 int pos=s.indexOf("=");//System.out.println(s+"  "+pos);
107                 if(pos==-1||pos==0);//return false;
108                 else{
109                     shuZhi[sum]=Double.valueOf(s.substring(s.indexOf("=")+1));
110                     bianLiang[sum++]=new String(s.substring(0,s.indexOf("=")));
111                 }
112             }
113         }catch(IOException e){
114             System.out.println("raise problem");
115             e.printStackTrace();
116             return false;
117         }
118         return true;
119     }
120     public static void main(String args[]) {//main函数
121         JFrame v=new JFrame();
122         FQiuHe a=new FQiuHe("D:/test.txt",v);
123     }
124     
125 }
FQiuHe.java
 1 package App;
 2 
 3 import javax.swing.JOptionPane;
 4 
 5 public class HuiWen{
 6     public static void main(String args[]){
 7         HuiWen a=new HuiWen();
 8     }
 9     public HuiWen(){
10         try{
11             String sa,sb;
12             StringBuffer SB;
13             do{
14                 while(true){
15                     sb=JOptionPane.showInputDialog(null,"请输入一个1~9999的整数","回文数",JOptionPane.INFORMATION_MESSAGE);
16                     if(sb.isEmpty()){
17                         JOptionPane.showMessageDialog(null,"还没输入呢...","回文数",JOptionPane.WARNING_MESSAGE);
18                         continue;
19                     }//输入是否为空
20                     try{
21                         if(Integer.parseInt(sb)<1 || Integer.parseInt(sb)>9999){
22                             JOptionPane.showMessageDialog(null,"请输入1~9999之间的整数...","回文数",JOptionPane.WARNING_MESSAGE);
23                             continue;
24                         }//输入错误
25                     }catch(NumberFormatException e){
26                         JOptionPane.showMessageDialog(null,"输入错误...","回文数",JOptionPane.WARNING_MESSAGE);
27                         continue;
28                     }//输入不合法控制    
29                     SB=new StringBuffer(sb);//调用reverse用StringBuffer
30                     sa=SB.reverse().toString(); //调用equals要用String,这里需要类型转换1
31                     if(true)break;
32                 }
33             }while(JOptionPane.showConfirmDialog(null,sb.equals(sa),"回文数",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE)==0);    
34         }catch(Exception e){}
35     }
36 }
HuiWen.java
  1 package App;
  2 
  3 import java.io.InputStream;
  4 import java.io.IOException;
  5 
  6 import javax.swing.JOptionPane;
  7 public class NumExchangeEnglish
  8 {
  9     private static String x[]={"zero","one","two","three","four","five","six","seven","eight","nine"} ; 
 10     private static String y[]={"ten","eleven","twelve","thirteen","fourteen","fifteen", "sixteen","seventeen","eighteen","nineteen"}; 
 11     private static String z[]={"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"};
 12 
 13 
 14     //按Col+Z结束状态标记
 15     private static boolean ok=true;
 16     //错误类型变量
 17     private static int ErrorState=0;
 18         //输入错误种类
 19         private static String ErrorKind[]={"其他错误输入.","数字应在0-99之间.","单词输入不合法."};
 20     //检测是不是num
 21     private static boolean CheckNum(StringBuffer a)
 22     {
 23         ErrorState=0;
 24         String temp=a.toString();
 25         temp=temp.trim();         //System.out.println(temp);
 26         //判断是否全是数字
 27         if(temp.charAt(0)=='0' && temp.length()!=1)return false;
 28         for(int i=0;i<temp.length();i++)
 29         {
 30             if(temp.charAt(i)<'0'||temp.charAt(i)>'9')return false;
 31         }
 32         //长度要小于2的数字才满足在0-99之间
 33         if(temp.length()>2){ErrorState=1;return false;}
 34         //判断是否满足0-99
 35         int num=Integer.parseInt(temp);
 36         if(num<0 || num>99)
 37         {
 38             ErrorState=1;
 39             return false;
 40         }
 41         //System.out.println(num);
 42         return true;
 43     }
 44     //检测是不是标准英语
 45     private static boolean CheckEnglish(StringBuffer a)
 46     {
 47         //如果已经是数字型的啦就不用考虑是英语转成数字问题啦
 48         if(ErrorState!=0)return false;
 49 
 50         int i;
 51         String temp=a.toString();
 52         temp=temp.trim();
 53         temp=temp.toLowerCase(); //System.out.println(temp);
 54         //按空格拆分
 55         int pos=temp.indexOf(' ');//System.out.println(pos);
 56         if(pos==-1)
 57         {
 58             int yes=0;
 59             for(i=0;i<10;i++)if(temp.equals(x[i]))return true;
 60                         for(i=0;i<10;i++)if(temp.equals(y[i]))return true;
 61             for(i=0;i<8;i++)if(temp.equals(z[i]))return true;
 62             ErrorState=2;
 63             return false;
 64         }
 65         else
 66         {
 67             //拆分成两个单词
 68             String ShiWei=temp.substring(0,pos);//System.out.println(ShiWei);
 69             int lastpos=temp.lastIndexOf(' ');
 70             if(lastpos==pos)//排除thirty one one情况
 71             {
 72                 String GeWei=temp.substring(lastpos+1);//System.out.println(GeWei);
 73                 //检测第一个单词是否合法(十位)
 74                                 int firstOk=0;
 75                 for(i=0;i<8;i++)if(ShiWei.equals(z[i])){firstOk=1;break;}
 76                 if(firstOk==0){ErrorState=2;return false;}
 77                 else 
 78                 {
 79                     for(i=1;i<10;i++)if(GeWei.equals(x[i])){firstOk=2;break;}
 80                     if(firstOk==1){ErrorState=2;return false;}
 81                 }
 82                 return true;
 83             }
 84             else
 85             {
 86                 ErrorState=2;
 87                 return false;
 88             }            
 89         }
 90     }
 91     //数字转英语
 92     private static void NumToEnglish(StringBuffer a)
 93     {
 94         String JieGuo;
 95         //转成int类num
 96         String temp=a.toString();
 97         temp=temp.trim();  
 98         int num=Integer.parseInt(temp);
 99         //一个单词可以搞定的直接输出
100         if(num<10)JieGuo=new String(x[num]);
101         else if(num<20)JieGuo=new String(y[num-10]);
102         else if(num==20)JieGuo=new String(z[0]);
103         else
104         {
105             //获取十位和个位数据
106             int ShiWei,GeWei;
107             ShiWei=num/10;GeWei=num%10;
108                     //转化成英语
109             if(GeWei==0)JieGuo=new String(z[ShiWei-2]);
110             else JieGuo=new String(z[ShiWei-2]+" "+x[GeWei]);            
111         }
112         JOptionPane.showConfirmDialog(null,a+"的翻译结果是:  "+JieGuo,"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
113     }
114     //英语转数字
115     private static void EnglishToNum(StringBuffer a)
116         {
117 
118         int i;
119         String temp=a.toString();
120         temp=temp.trim();
121         temp=temp.toLowerCase(); //System.out.println(temp);
122         //按空格拆分
123         int pos=temp.indexOf(' ');//System.out.println(pos);
124         if(pos==-1)
125         {
126             for(i=0;i<10;i++)if(temp.equals(x[i])){
127                 //System.out.println(i);
128                 JOptionPane.showConfirmDialog(null,a+"的翻译结果是:  "+(i),"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
129                 return;
130             }
131             for(i=0;i<10;i++)if(temp.equals(y[i])){
132                 //System.out.println(i+10);
133                 JOptionPane.showConfirmDialog(null,a+"的翻译结果是:  "+(i+10),"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
134                 return;
135             }
136             for(i=0;i<8;i++)if(temp.equals(z[i])){
137                 //System.out.println((i+2)*10);
138                 JOptionPane.showConfirmDialog(null,a+"的翻译结果是:  "+((i+2)*10),"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
139                 return;
140             }
141         }
142         else
143         {
144             //拆分成两个单词
145             String ShiWei=temp.substring(0,pos);//System.out.println(ShiWei);
146             int lastpos=temp.lastIndexOf(' ');
147             String GeWei=temp.substring(lastpos+1);//System.out.println(GeWei);
148             int sum=0;
149             for(i=0;i<8;i++)if(ShiWei.equals(z[i])){sum+=(i+2)*10;break;}    
150             for(i=0;i<10;i++)if(GeWei.equals(x[i])){sum+=i;break;}
151             //System.out.println(sum);
152             JOptionPane.showConfirmDialog(null,a+"的翻译结果是:  "+sum,"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
153         }
154     }
155     //读入一行返回String
156     private static StringBuffer ReadLine(InputStream in){
157         StringBuffer SB=new StringBuffer();
158         try {  
159           while(true){
160             
161             int i=in.read();
162             while(i!='\n' && i!=-1)
163             {
164                 SB.append((char)i);
165                 i=in.read();
166             }
167             System.out.println(i);
168             if(i==-1)
169             {
170                 ok=false;
171                 return SB;
172             }
173             String data=SB.toString();
174             data=data.trim();
175             if(data.length()==0)continue;//System.out.println(data.length());
176             return SB;
177           }
178         }
179         catch(IOException e)
180         {
181             System.err.println("发生异常:"+e);
182             e.printStackTrace();
183             return SB;
184         }
185     }
186     public NumExchangeEnglish(){
187         StringBuffer data;
188         String s;
189         try{
190             while(ok){
191                 s=JOptionPane.showInputDialog(null,"请输入待翻译的数","中英互译",JOptionPane.INFORMATION_MESSAGE);
192                 if(s.isEmpty()){
193                     JOptionPane.showMessageDialog(null,"还没输入呢...","回文数",JOptionPane.WARNING_MESSAGE);
194                     continue;
195                 }
196                 data=new StringBuffer(s);                
197                 if(ok==false)return;
198                 if(CheckNum(data)==true)NumToEnglish(data);
199                 else if(CheckEnglish(data)==true)EnglishToNum(data);
200                 else{
201                     JOptionPane.showMessageDialog(null,ErrorKind[ErrorState],"回文数",JOptionPane.WARNING_MESSAGE);
202                 }    
203             }
204         }catch(Exception e){}
205     }
206     public static void main(String args[]){
207         NumExchangeEnglish a=new NumExchangeEnglish();
208     }
209 }
NumExchangeEnglish.java

 

posted @ 2014-02-18 19:20  beautifulzzzz  阅读(2596)  评论(4编辑  收藏  举报