本來是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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }

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 }

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 }

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 }

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 }
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 }
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 }

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 }

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 }

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 }