编写一个具有菜单以及编辑、查找、替换、复制、粘贴功能,且具有新建、打开和保存文件功能的记事本(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;
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 = new MenuBar();
menuBar.setStyle("-fx-background-color:lightgray");
Menu menuFile = new Menu("文件(F)");
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("确定新建文件吗??");
Optional<ButtonType> buttonType = alert.showAndWait();
if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) {
textArea.setText(" ");
primaryStage.setTitle("新建文件");
}
});
MenuItem menuOpen = new MenuItem("打开(O)...");
menuOpen.setAccelerator(KeyCombination.valueOf("Ctrl+O"));
menuOpen.setOnAction((final ActionEvent e) -> {
File file = fileChooser.showOpenDialog(primaryStage);
if (file != null) {
openFile(file);
}
});
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(" 此文件未保存");
});
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("确定要退出吗?");
Optional<ButtonType> buttonType = alert.showAndWait();
if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) {
System.exit(0);
}
});
menuFile.getItems().addAll(menuNew, menuOpen, separator1, menuSave, menuSaveAs, separator2, menuExit);
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 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.getMenus().addAll(menuFile, menuEdit, menuHelp);
textArea = new TextArea();
BorderPane mainPane = new BorderPane();
mainPane.setTop(menuBar);
mainPane.setCenter(textArea);
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("确定要退出记事本吗?");
Optional<ButtonType> buttonType = alert.showAndWait();
if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) {
System.exit(0);
}
});
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,5,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, 5, 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, 5, 20, 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, 5, 20, 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) {
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();
}
});
}
}