基於Java實現記事本功能
阿新 • • 發佈:2021-01-04
本文例項為大家分享了Java實現記事本的具體程式碼,供大家參考,具體內容如下
編寫一個具有選單以及編輯、查詢、替換、複製、貼上功能,且具有新建、開啟和儲存檔案功能的記事本(MyNotepad)。
package ch7; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Optional; import javafx.scene.control.TextField; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TextArea; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DataFormat; import javafx.scene.input.KeyCombination; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import javafx.stage.WindowEvent; //編寫一個具有選單以及編輯、查詢、替換、複製、貼上功能,且具有新建、開啟和儲存檔案功能的記事本(MyNotepad)。 public class MyNotePad extends Application { public static TextArea textArea;//文字框的範圍 public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { // 檔案選取器 final FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Text Files","*.txt"),//加入格式 new ExtensionFilter("Java Sourse Files","*.java")); // 建立MenuBar MenuBar menuBar = new MenuBar();// menuBar.setStyle("-fx-background-color:lightgray"); /************************************ * 建立 Menu,檔案選單條 ************************************/ Menu menuFile = new Menu("檔案(F)"); //1.新建 MenuItem menuNew = new MenuItem("新建"); menuNew.setAccelerator(KeyCombination.valueOf("Ctrl+N")); menuNew.setOnAction((final ActionEvent e)-> { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); // 建立一個訊息對話方塊,僅僅提供確定按鈕 alert.setHeaderText("新建檔案"); // 設定對話方塊的頭部文字 // 設定對話方塊的內容文字 alert.setContentText("確定新建檔案嗎??"); //alert.show(); // 顯示對話方塊 Optional<ButtonType> buttonType = alert.showAndWait(); // 判斷返回的按鈕型別是確定還是取消,再據此分別進一步處理 if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) { // 單擊了確定按鈕OK_DONE textArea.setText(" ");//清空文字框內 primaryStage.setTitle("新建檔案"); } }); //2.開啟 MenuItem menuOpen = new MenuItem("開啟(O)..."); // 設定menuItem的快捷鍵 menuOpen.setAccelerator(KeyCombination.valueOf("Ctrl+O")); menuOpen.setOnAction((final ActionEvent e) -> { File file = fileChooser.showOpenDialog(primaryStage); if (file != null) { openFile(file); } }); //3.儲存 MenuItem menuSave = new MenuItem("儲存(S)"); menuSave.setAccelerator(KeyCombination.valueOf("Ctrl+S")); menuSave.setOnAction((final ActionEvent e) -> { FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)","*.txt"); File file = fileChooser.showSaveDialog(primaryStage); saveFile(file); if(file.getAbsolutePath()!=null) { System.out.print(file.getName()+"已經報存在:"+file); } else System.out.println(" 此檔案未儲存"); }); //4.另存 MenuItem menuSaveAs = new MenuItem("另存(A)..."); menuSaveAs.setOnAction((final ActionEvent e) -> { FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)","*.txt"); File file = fileChooser.showSaveDialog(primaryStage); saveFile(file); if(file.getAbsolutePath()!=null) { System.out.print(file.getName()+"已經另存在:"+file); } else System.out.println(" 此檔案未儲存"); }); // 建立分割線 SeparatorMenuItem separator1 = new SeparatorMenuItem(); SeparatorMenuItem separator2 = new SeparatorMenuItem(); MenuItem menuExit = new MenuItem("退出"); menuExit.setOnAction((ActionEvent e) -> { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); // 建立一個確認對話方塊 //判斷文字框是否為空 if(!textArea.getText().isEmpty()) { alert.setHeaderText("還有內容未儲存,你確定要退出嗎?"); }// 設定對話方塊的頭部文字 else alert.setHeaderText("確定要退出嗎?"); // 設定對話方塊的內容文字 // alert.setContentText("確定要退出MyNotePad嗎?"); // 顯示對話方塊,並等待按鈕返回 Optional<ButtonType> buttonType = alert.showAndWait(); // 判斷返回的按鈕型別是確定還是取消,再據此分別進一步處理 if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) { // 單擊了確定按鈕OK_DONE System.exit(0); } }); // 將MenuItem放在對應的Menu上e menuFile.getItems().addAll(menuNew,menuOpen,separator1,menuSave,menuSaveAs,separator2,menuExit);// 將分割線加進來 /************************************ * 建立 Menu,編輯選單條 ************************************/ Menu menuEdit = new Menu("編輯(E)"); / MenuItem menuSelctAll = new MenuItem("全選(A)"); menuSelctAll.setAccelerator(KeyCombination.valueOf("Ctrl+A")); menuSelctAll.setOnAction((final ActionEvent e)->{ selectAll(); }); MenuItem menuCut = new MenuItem("剪下"); menuCut.setOnAction((final ActionEvent e)->{ cutMethod(); }); menuCut.setAccelerator(KeyCombination.valueOf("Ctrl+X")); MenuItem menuCopy = new MenuItem("複製(C)"); menuCopy.setOnAction((final ActionEvent e)->{ copyMethod(); }); menuCopy.setAccelerator(KeyCombination.valueOf("Ctrl+C")); / MenuItem menuPaste = new MenuItem("貼上(P)"); menuPaste.setAccelerator(KeyCombination.valueOf("Ctrl+V")); menuPaste.setOnAction((final ActionEvent e)->{ pasteMethod(); }); // 建立分割線 SeparatorMenuItem separator3 = new SeparatorMenuItem(); // 查詢替換選單項 MenuItem menuFind = new MenuItem("查詢(F)"); menuFind.setOnAction((final ActionEvent e)->{ findMethod(); }); MenuItem menuReplace = new MenuItem("替換(R)..."); menuReplace.setOnAction((final ActionEvent e)->{ replaceMethod(); }); menuEdit.getItems().addAll(menuSelctAll,menuCut,menuCopy,menuPaste,separator3,menuFind,menuReplace); // 建立 幫助子選單 Menu Menu menuHelp = new Menu("幫助(H)"); MenuItem menuGuide = new MenuItem("指南(D)"); menuGuide.setOnAction((ActionEvent e) -> { // 設定按鈕的單擊事件 Alert alert = new Alert(Alert.AlertType.INFORMATION); // 建立一個訊息對話方塊 alert.setHeaderText("指南"); // 設定對話方塊的頭部文字 // 設定對話方塊的內容文字 alert.setContentText("指南正在努力編寫中,敬請期待。。。"); alert.show(); // 顯示對話方塊 }); MenuItem menuAbout = new MenuItem("關於(A)"); menuAbout.setOnAction((ActionEvent e) -> { // 設定按鈕的單擊事件 Alert alert = new Alert(Alert.AlertType.INFORMATION); // 建立一個訊息對話方塊 alert.setHeaderText("關於本軟體"); // 設定對話方塊的頭部文字 // 設定對話方塊的內容文字 alert.setContentText("JAVA記事本 版權所有 @2035"); alert.show(); // 顯示對話方塊 }); menuHelp.getItems().addAll(menuGuide,menuAbout); // MenuBar,裝入各選單條 menuBar.getMenus().addAll(menuFile,menuEdit,menuHelp); // 建立MenuItem類 // 還可以對MenuItem設定圖示 // 將menuBar加入到佈局類mainPane上 // 文字編輯元件 textArea = new TextArea(); // 建立佈局類,放置編輯區域 BorderPane mainPane = new BorderPane(); mainPane.setTop(menuBar); mainPane.setCenter(textArea); // 建立場景圖 // Scene scene = new Scene(anchorPane); Scene scene = new Scene(mainPane); primaryStage.setScene(scene); primaryStage.setHeight(800); primaryStage.setWidth(700); primaryStage.setTitle("無標題-記事本"); // 使用者點選關窗按鈕時 ...... primaryStage.setOnCloseRequest((WindowEvent event) -> { // 嚴格的話,需判斷檔案儲存與否,或確認是否退出 Alert alert = new Alert(Alert.AlertType.INFORMATION); // 建立一個確認對話方塊,提供一個確認影象,和確認取消按鈕 alert.setHeaderText("確定要退出記事本嗎?"); // 設定對話方塊的頭部文字 // 設定對話方塊的內容文字 // alert.setContentText("確定要退出MyNotePad嗎?"); // 顯示對話方塊,並等待按鈕返回 Optional<ButtonType> buttonType = alert.showAndWait(); // 判斷返回的按鈕型別是確定還是取消,再據此分別進一步處理 if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) { // 單擊了確定按鈕OK_DONE System.exit(0); }//不知道怎麼用取消返回,所以改成了INFORMATION }); primaryStage.show(); } //開啟 private void openFile(File file) { textArea.setText(""); try { BufferedReader in = new BufferedReader(new FileReader(file)); String line; while ((line = in.readLine()) != null) textArea.appendText(line + "\n"); in.close(); textArea.positionCaret(0); } catch (IOException ioe) { System.err.println(ioe); } } //儲存 public void saveFile(File file) { try { PrintWriter print=new PrintWriter(new BufferedWriter(new FileWriter(file))); print.write(textArea.getText()); print.flush(); print.close(); }catch(IOException ioe) { ioe.printStackTrace();; } } //複製 public void copyMethod() { //獲取剪下板 Clipboard clipboard=Clipboard.getSystemClipboard(); ClipboardContent content=new ClipboardContent();// //選取文字 String temp=textArea.getSelectedText();//獲得已經選取的內容 //將獲取的內容放到系統剪下板 content.putString(temp); //把內容放在文字剪下板 clipboard.setContent(content); } //剪下 public void cutMethod() { //獲得系統剪下板 Clipboard clip=Clipboard.getSystemClipboard(); ClipboardContent content=new ClipboardContent(); //獲取選中 String temp=textArea.getSelectedText(); //把選中放入剪下板 content.putString(temp); //放入文字剪貼簿 clip.setContent(content); //選中內容用""代替 textArea.replaceSelection(""); } //貼上 public void pasteMethod() { Clipboard clip=Clipboard.getSystemClipboard(); ClipboardContent content=new ClipboardContent(); Clipboard c=clip.getSystemClipboard(); if(c.hasContent(DataFormat.PLAIN_TEXT)); { String s=c.getContent(DataFormat.PLAIN_TEXT).toString(); if(textArea.getSelectedText()!=null) {//選中不為空 textArea.replaceSelection(s); } else {//如果滑鼠為選中,從後邊貼 int mouse=textArea.getCaretPosition();//插入符號在文字中當前位置 textArea.insertText(mouse,s); } } } //全選 public void selectAll() { textArea.selectAll();//全選 } //查詢,參照網頁程式碼 int startIndex=0; public void findMethod() { HBox h1=new HBox(); h1.setPadding(new Insets(20,5,20,5)); h1.setSpacing(5); Label label1=new Label("查詢內容(N):"); TextField tf1=new TextField(); h1.getChildren().addAll(label1,tf1); VBox v1=new VBox(); v1.setPadding(new Insets(20,10)); Button btn1=new Button("查詢下一個"); v1.getChildren().add(btn1); HBox findRootNode=new HBox(); findRootNode.getChildren().addAll(h1,v1); Stage findStage=new Stage(); Scene scene1=new Scene(findRootNode,450,90); findStage.setTitle("查詢"); findStage.setScene(scene1); findStage.setResizable(false);//固定視窗大小 findStage.show(); btn1.setOnAction((ActionEvent e)->{ String textString=textArea.getText(); String tfString=tf1.getText(); if(!tf1.getText().isEmpty()) { if(textString.contains(tfString)) { if(startIndex==-1) { Alert alert1=new Alert(AlertType.WARNING); alert1.titleProperty().set("提示"); alert1.headerTextProperty().set("我找不著"); alert1.show(); } startIndex=textArea.getText().indexOf(tf1.getText(),startIndex); if(startIndex>=0&&startIndex<textArea.getText().length()) { textArea.selectRange(startIndex,startIndex+tf1.getText().length()); startIndex+=tf1.getText().length(); } } if(!textString.contains(tfString)) { Alert alert1=new Alert(AlertType.WARNING); alert1.titleProperty().set("提示"); alert1.headerTextProperty().set("我找不著"); alert1.show(); } } else if(tf1.getText().isEmpty()) { Alert alert1=new Alert(AlertType.WARNING); alert1.titleProperty().set("出錯"); alert1.headerTextProperty().set("輸入內容為空。"); alert1.show(); } }); } //這段是參照網頁程式碼 public void replaceMethod() { HBox h1 = new HBox(); h1.setPadding(new Insets(20,10,8)); h1.setSpacing(5); Label label1 = new Label("查詢下一個(F)"); TextField tf1 = new TextField(); h1.getChildren().addAll(label1,tf1); HBox h2 = new HBox(); h2.setPadding(new Insets(5,8)); h2.setSpacing(5); Label label2 = new Label("替換內容(N):"); TextField tf2 = new TextField(); h2.getChildren().addAll(label2,tf2); VBox v1 = new VBox(); v1.getChildren().addAll(h1,h2); VBox v2 = new VBox(); v2.setPadding(new Insets(21,10)); v2.setSpacing(13); Button btn1 = new Button("查詢下一個"); Button btn2 = new Button("替換為"); v2.getChildren().addAll(btn1,btn2); HBox replaceRootNode = new HBox(); replaceRootNode.getChildren().addAll(v1,v2); Stage replaceStage = new Stage(); Scene scene = new Scene(replaceRootNode,430,120); replaceStage.setTitle("替換"); replaceStage.setScene(scene); replaceStage.setResizable(false); // 固定視窗大小 replaceStage.show(); btn1.setOnAction((ActionEvent e) -> { String textString = textArea.getText(); // 獲取記事本文字域的字串 String tfString = tf1.getText(); // 獲取查詢內容的字串 if (!tf1.getText().isEmpty()) { if (textString.contains(tfString)) { if (startIndex == -1) {// not found Alert alert1 = new Alert(AlertType.WARNING); alert1.titleProperty().set("提示"); alert1.headerTextProperty().set("已經找不到相關內容了!!!"); alert1.show(); } startIndex = textArea.getText().indexOf(tf1.getText(),startIndex); if (startIndex >= 0 && startIndex < textArea.getText().length()) { textArea.selectRange(startIndex,startIndex+tf1.getText().length()); startIndex += tf1.getText().length(); } btn2.setOnAction((ActionEvent e2) -> { if(tf2.getText().isEmpty()) { //替換內容為空時 Alert alert1 = new Alert(AlertType.WARNING); alert1.titleProperty().set("出錯了"); alert1.headerTextProperty().set("替換內容為空"); alert1.show(); }else { //替換內容不為空則替換 textArea.replaceSelection(tf2.getText()); } }); } if (!textString.contains(tfString)) { Alert alert1 = new Alert(AlertType.WARNING); alert1.titleProperty().set("提示"); alert1.headerTextProperty().set("找不到相關內容了!!!"); alert1.show(); } } else if (tf1.getText().isEmpty()) { Alert alert1 = new Alert(AlertType.WARNING); alert1.titleProperty().set("出錯了"); alert1.headerTextProperty().set("輸入內容為空"); alert1.show(); } }); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。