This article introduces the detailed process of Java writing notepad based on SWT. It is shared with you for your reference. The specific content is as follows
It can realize the basic functions of desktop notepad in Windows system, fool-style teaching, and step-by-step operation. Xiaobai can also write a complete application by himself.
Required tools: Eclipse (with SWT plug-in)
The finished product is as follows:
Application function introduction:
Functional analysis:
The file menu includes
1.1. Create (N) Ctrl+N
1.2Open (O) Ctrl+O
1.3Save(S) Ctrl+S
1.4Save as (A)
1.5 Exit (X)
The edit menu includes:
2.1 Undo (U) Ctrl+Z
2.2 Shear (T) Ctrl+T
2.3 Copy (C) Ctrl+C
2.4 Paste (P) Ctrl+V
2.5 Delete (L) Del
2.6 Find (D) Ctrl+F
2.7 Find the next place (N) F3
2.8 Replace (R) Ctrl+H
2.9 Go to (G) Ctrl+G
2.10 Select all (A) Ctrl+A
2.11 Time/Date (D) F5
The format menu includes
3.1 Automatic line wrap (W)
3.2 Font (F)
The view menu includes
4.1 Status Bar (S)
The help menu includes
5.1 View Help (H)
5.2 About Notepad (A)
Next, I will teach you step by step to write a notepad with several specific categories as follows:
1.NotePad.java
This class is the main interface class, which contains the listening events of each button
2. Util.java class This class is a auxiliary class, which facilitates calling members defined in the main window class in other classes.
3. AboutAuthor.java
About the author's class, a Dialog window for displaying author information
4.FindWindow.java
A Dialog window for the search function
5.Go_To.java
Go to a Dialog window of the function
6.OpenMethod.java
There are two ways to open a file encapsulated
7.SavaMethod.java
Two ways to save files
8.SWTRsourceManager.java
This class is an externally imported class and is used to load images
9.test.java
Program entry, convenient package jar files later
10.QuitMethod.java
Two ways to close the window are encapsulated
Writing steps:
one. Create a new SWT project and create the first window
Open Eclipse, new->other->WindowBuilder->SWT Designer->SWT/JFace Java Project. Name the project name NotePad
Open the newly created NotePad project, right-click new->Package at scr to create a new package, named com.chance.org
tips: The naming rules of packages are best used to use com. custom.org. Don’t ask why, you will understand after working in the future.
Right-click the newly created package new->other->WindowBuilder->SWT Designer->SWT ->Application Window Name NotePad
At this point, we built the first SWT window and clicked on the design on the right side of the source to view the graphical interface of the newly created number to realize visual programming.
Rename the txt property in the Properties in the NotePad form to: NotePad
Drag the Composites component in Composites into the NotePad component, and modify its Layout property to FillLayout, that is, a fill layout, so that the entire interface can be turned into an editing domain later. Then drag the text component into the Composites component. Check the h_scroll attribute and v_scroll attribute in the property Style of the text component to true
Description: h_scroll is a horizontal scroll bar, v_scroll is a vertical scroll bar
two. Set the related labels of the menu bar and the overall layout of the form
Select Menu bar component to drag it into the main form
1. Set the first menu item (file)
Select the Cascde Menu component, drag it into the Menu bar component, and modify the attribute: modify the variable attribute to file_menu, and modify the text to file (F);
1.1 Settings submenu: Create (N) Ctrl+N
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to new_file, and modify the text to: New (N) Ctrl+N;
1.2 Settings submenu: Open (O) Ctrl+O
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to open_file, and modify the text to: Open (O) Ctrl+O
1.3 Settings submenu: Save (O) Ctrl+S
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to save_file, and modify the text to: Save (O) Ctrl+S
1.4 Settings submenu: Save as (A)
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to save_as, and modify the text to: Save as (A)
1.5 Settings submenu: Exit (X)
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to quit, and modify the text to: Exit (X)
2. Set the second menu item (edit)
Select the Cascde Menu component, drag it into the Menu bar component, and modify the attribute: modify the variable attribute to edit_menu, and modify the text to edit (E);
2.1 Settings submenu: Undo (U) Ctrl+Z
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to undo, and modify the text to: Undo (U) Ctrl+Z, and change enable to false;
2.2 Settings submenu: Cut (T) Ctrl+T
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to cut, and modify the text to: Cut (T) Ctrl+T, and change enable to false;
2.3 Settings submenu: Copy (C) Ctrl+C
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to copy, and modify the text to: Copy (C) Ctrl+C, and change enable to false;
2.4 Settings submenu: Paste (P) Ctrl+V
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to paste, and modify the text to: Paste (P) Ctrl+V
2.5 Settings submenu: Delete (L) Del
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to delete, and modify the text to: Delete (L) Del, and change enable to false;
2.6 Settings submenu: Find (D) Ctrl+F
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to find, and modify the text to: Find (D) Ctrl+F, and change enable to false;
2.7 Settings submenu: Find the next place (N) F3
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to find_next, and modify the text to: Find the next place (N) F3, and change enable to false;
2.8 Settings submenu: Replace (R) Ctrl+H
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to replace, and modify the text to: Replace (R) Ctrl+H, and change enable to false;
2.9 Settings submenu: Go to (G) Ctrl+G
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to go_to, and modify the text to: Go to (G) Ctrl+G
2.10 Settings submenu: Select all (A) Ctrl+A
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to selectAll, and modify the text to: Select all (A) Ctrl+A
2.11 Settings submenu: Time/Date (D) F5
Select Menu Item to add to the Cascde Menu component, modify the attribute: change the variable attribute to showDate, and modify the text to: Time/Date (D) F5
3. Set the third menu item (format)
Select the Cascde Menu component, drag it into the Menu bar component, and modify the attribute: modify the variable attribute to format_menu, and modify the text to format (O);
3.1 Settings submenu: Automatic line wrap (W)
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to auto_Enter, and modify the text to: Automatic line wrap (W)
3.2 Settings submenu: Font (F)
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to setFont, and modify the text to: Font (F)
4. Set the fourth menu item (View)
Select the Cascde Menu component, drag it into the Menu bar component, and modify the attribute: modify the variable attribute to view_menu, and modify the text to view (V);
4.1 Settings submenu: Status Bar (S)
Select Menu Item to add to the Cascde Menu component, modify the attribute: modify the variable attribute to state, and modify the text to: Status bar (S)
5. Set the fifth menu item (Help)
Select the Cascde Menu component, drag it into the Menu bar component, and modify the attribute: modify the variable attribute to help_menu, and modify the text to help (H);
5.1 Settings submenu: View Help (H)
Select Menu Item to add it to the Cascde Menu component, modify the attribute: change the variable attribute to lookHelp, and modify the text to: View Help (H)
5.2 Settings submenu: About Notepad (A)
Select Menu Item to add it to the Cascde Menu component, modify the attribute: change the variable attribute to aboutAuthor, and modify the text to: About Notepad (A)
At this point, the rendering of the entire page layout has been set as follows:
Next, implement various functions
three. Settings menu shortcut keys
Introduction to the setAccelerator() function : Use the setAccelerator() function to set the relevant shortcut keys. The passed parameters are key values. For example, the shortcut key Ctrl+N is set as: object. setAccelerator(SWT.CTrl+'N');
The shortcut key F5 setting method is: object.setAccelerator(SWT.F5);
From this we can set all the required shortcut keys
new_file.setAccelerator(SWT.CTRL + 'N'); //Create a new file shortcut open_file.setAccelerator(SWT.CTRL + 'O'); //Save a file shortcut undo.setAccelerator(SWT.CTRL + 'Z'); //Undo a shortcut cut.setAccelerator(SWT.CTRL + 'T'); //Cut a shortcut copy.setAccelerator(SWT.CTRL + 'C'); //Copy a shortcut paste.setAccelerator(SWT.CTRL + 'V'); //Paste the shortcut key delete.setAccelerator(SWT.DEL); //Delete the shortcut key find.setAccelerator(SWT.CTRL + 'F'); //Find the shortcut key find_next.setAccelerator(SWT.F3); //Find the next shortcut key replace.setAccelerator(SWT.CTRL + 'H'); //Replace the shortcut key go_to.setAccelerator(SWT.CTRL + 'G'); //Go to the shortcut key selectAll.setAccelerator(SWT.CTRL + 'A');//Select all shortcut keys showDate.setAccelerator(SWT.F5); //Show time shortcut keys
4. Add event listening function (1) file class
Add event listening function to each menu of the file
1. Add the "Exit" menu listening event
Function description: The implementation of triggering this menu to exit the application is relatively simple. Call the system function System.exit(0); you can click the "Time/Date (F5)" component in design mode and then click "Show event"->selection->Double-click widgetSelected
The event code is as follows:
quit.addSelectionListener(new SelectionAdapter() { /** * Add the listening event of the "Exit" menu* Function description: Triggering this menu will exit the application*/ public void widgetSelected(SelectionEvent e) { System.exit(0); } });But is the fact that simple? In fact, it is not the case that you can just click to exit and then exit directly. There are still hints when quitting in a real notepad, so the improved code is as follows;
public void DIYquit(){ /** * When exiting the function, determine whether it is necessary to save it*/ String tips; System.out.println(Util.shell.getText().getText()); if(Util.shell.fileDir != null || Util.shell.getText().getText() != ""){ //The file directory is not empty, which means there is an open file. You need to ask whether to save it if(Util.shell.fileDir == null){ tips = "The untitled text of the file has changed. /n"+"Do you want to save the file?"; }else{ tips = "File" +Util.shell.fileDir + " The text of " has changed. /n"+"Do you want to save the file?" } int n=JOptionPane.showConfirmDialog(null, tips,"Notepad",JOptionPane.YES_NO_CANCEL_OPTION); if(n==0){ //Yes return 0 No Return 1 Cancel Return 2 SaveMethod savemethod = new SaveMethod(); savemethod.Save(); //Point yes, save the file and open the file}else if(n==1){ //Return No System.exit(0); }else if(n==2){ //Return Cancel return ; } System.exit(0); }else{ if(Util.shell.getText().getText() != ""){ //If the directory is empty but the content is not empty, it means there is content but it has not been saved. The tips = "The untitled text of the file has changed. /n"+"Do you want to save the file?"; int n=JOptionPane.showConfirmDialog(null, tips,"Notepad",JOptionPane.YES_NO_CANCEL_OPTION); if(n==0){ //Yes return 0 No Return 1 Cancel Return 2 SaveMethod savemethod = new SaveMethod(); savemethod.Save(); //Point yes, save the file and open the file}else if(n==1){ //Return No System.exit(0); }else if(n==2){ //Return Cancel return; } System.exit(0); }else{ } } System.exit(0); }I define each operation in the next listening event as a function. The listening event addition method is the same as the first step. The specific implementation method is as follows:
2. Add the "Save As" menu to listen events
Function description: Trigger this menu and the save as window will pop up, and save the file as elsewhere. In order to facilitate the reuse of the code, save as encapsulate it into a method and call the code as follows:
public void SaveAs(){ /** * Encapsulate it as this method to facilitate call*/ FileDialog dialog = new FileDialog(Util.shell.shell,SWT.SAVE); dialog.setFilterPath(System.getProperty("C://Documents and Settings"));//Set the default path to open dialog.setFilterExtensions(new String[] {"*.txt", "*.*"}); //Set the extension of the opened file dialog.setFilterNames( new String[]{"Text Files (*.txt)", "All Files (*.*)"}); //Set the name of the extension displayed in the drop-down box String file = dialog.open();//Open the window and return to the file directory selected by the user if(file != null){ Util.shell.fileDir = file;//Save the file directory, use later} if ( file != null ) { Util.shell.shell.setText((new File( file.trim())).getName());//Get the file name (excluding path) to set the title FileWriter fileWriter; try { fileWriter = new FileWriter(file); BufferedWriter out = new BufferedWriter(fileWriter); out.write(Util.shell.getText().getText()); out.close(); fileWriter.close(); } catch (IOException e1) { e1.printStackTrace(); } } }3. Add the "Save" menu listening event
Function Description: When the "Save" menu is triggered, the save file window pops up, and then select the directory and enter the file name to save. Regarding the logic of saving, I have to talk about the saving here: At the beginning, I was thinking about how to determine whether the current document is saved or saved as. Later, I carefully observed the desktop notepad and found that the dialog box popped up by Save and Save as is the same. You only need to make a slight difference to determine whether to save or save as the judgment is as follows: If it is saved, it means that fileDir exists, and you can directly call the saved function. If fileDir does not exist, it means that the file is newly opened and the path has not been determined yet, so jump to Save as form.
First, define a global variable String fileDir = null; assign it to empty, and all files are not saved by default. Then, whether it is to open the file or save it as a file, the directory where the file is located (including the file name and suffix name) is recorded in fileDir, and finally determine whether fileDir is empty in the save event.
The code is as follows:
public void Save(){ /** * Save file*/ if(Util.shell.fileDir!=null ){ // means that the file has a directory and saves it directly when saving, and there is no need to pop-up Util.shell.shell.setText((new File( Util.shell.fileDir.trim())).getName()); // Get the file name (excluding path) to set the title FileWriter fileWriter; try { fileWriter = new FileWriter(Util.shell.fileDir); BufferedWriter out = new BufferedWriter(fileWriter); out.write(Util.shell.getText().getText()); out.close(); fileWriter.close(); } catch (IOException e1) { e1.printStackTrace(); } } else{// Otherwise, it is never saved, then save as window SaveAs(); } }4. Add the "Open" menu listening event
Function description: When the "Open" menu is triggered, the open file window pops up, and then select the file to open. In order to reuse the code, the opening method is encapsulated into function code as follows:
public void OpenFile(){ if(Util.shell.fileDir != null || Util.shell.getText().getText() != ""){ String tips = "file" +Util.shell.fileDir + " The text of " has changed. /n"+"Do you want to save the file?"; int n=JOptionPane.showConfirmDialog(null, tips,"Notepad",JOptionPane.YES_NO_CANCEL_OPTION); if(n==0){ //Yes return 0 No return 1 Cancel Return 2 SaveMethod savemethod = new SaveMethod(); savemethod.Save(); //Does yes, save the file and open the file}else if(n==1){ //Return No}else if(n==2){ //Return Cancel return ; } }else{ FileDialog dialog = new FileDialog(Util.shell.shell,SWT.OPEN); dialog.setFilterPath(System.getProperty("C://Documents and Settings"));//Set the default path to open dialog.setFilterExtensions(new String[] {"*.txt", "*.*"});//Set the extension of the opened file dialog.setFilterNames( new String[]{"Text Files (*.txt)", "All Files (*.*)"});//Set the name of the extension displayed in the drop-down box String file = dialog.open();//Open the window and return the file directory selected by the user (including file name) if(file == null){ return ; } Util.shell.fileDir = file; Util.shell.shell.setText((new File( file.trim())).getName());//Get the file name (excluding path) to set the title FileReader filereader; try { filereader = new FileReader(file); BufferedReader in = new BufferedReader(filereader); String s = null; Util.shell.getText().setText(""); //Empty the edit box content try { while((s=in.readLine())!=null){ Util.shell.getText().append(s+"/n"); } } catch (IOException e1) { e1.printStackTrace(); } } catch (FileNotFoundException e2) { e2.printStackTrace(); } } }5. Add the "New" menu listening event
Function description: When the event is triggered, create a new window. If the current file is not saved, it is prompted to save it, otherwise a new page will be jumped to generate.
The principle of generating a new page: re-initialize the title, initialize fileDir, and initialize the editing domain. Here you extract the code to open the new file into a method, which is convenient to call the code as follows:
void openNewFile() { if(Util.shell.fileDir != null || Util.shell.getText().getText() != ""){ String tips = "File" +Util.shell.fileDir + " The text of "has changed. /n"+"Do you want to save the file?"; int n=JOptionPane.showConfirmDialog(null, tips,"Notepad",JOptionPane.YES_NO_CANCEL_OPTION); if(n==0){ //Yes return 0 No return 1 Cancel Return 2 SaveMethod savemethod = new SaveMethod(); //Do it yes, then save the file and open the file}else if(n==1){ //Return No}else if(n==2){ //Return Cancel return ; } String t = "Unt title(" + ++Util.shell.cnt + ") - Notepad"; Util.shell.shell.setText(t); //Set the title Util.shell.getText().setText(""); //Clear the edit box Util.shell.fileDir = null; }else{ String t = "Unt title(" + ++Util.shell.cnt + ") - Notepad"; Util.shell.shell.setText(t); //Set the title Util.shell.getText().setText(""); //Clear the edit box Util.shell.fileDir = null; } //All data is initialized}4. Add event listening function (2) Editorial class
Add event listening function for each menu
1. Add the "Show Time" menu to listen events
Function description: When the event is triggered, the system time will be displayed at the cursor in the edit box: Obtain the current system time, convert it into a String type, and then call the text.append(str) method to display the time after the edit box cursor.
1.1 Add an event listening function to get the current time method of the system: call SimpleDateFormat object to format the time, and then call Date to get the time.
The problem at the beginning: it can only be added to the end of the content every time. If you think about it carefully, you must locate the current cursor position, and then splice the string before the cursor + the string after the cursor, and then display it together.
I searched for a long time and found that getCaretPosition() just returned as plastic, which should be the one that gets the current cursor position. I tried it as expected. Next is to implement string splicing technology: s1.substring(0, index) + s2 + s1.substring(index, s1.length());
The returned new string.
Problems that arise: After splicing, the output is directly generated, resulting in the previous content being spliced with the new strings later. After a long time of change, I found that I need to call the setText(String) method. Before output, clear the content displayed in the previous editing box first. The final listening function content is as follows:
showDate.addSelectionListener(new SelectionAdapter() { /** * Add the listening event of the "Time and Date" menu* Function description: Trigger this menu to add the current system time to the end of the cursor of the edit box*/ public void widgetSelected(SelectionEvent e) { int index = getText().getCaretPosition(); //Get the position of the cursor in the current edit box//System.out.println(index); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//Set the date format String localTime = df.format(new Date()); String newString = insertString(getText().getText(),localTime,index); //The spliced string getText().setText(""); //Clear the content of the original editing box and display the new content//System.out.println(localTime); //New Date() is to get the current system time getText().append(newString); //Show the spliced string} });The splicing string function is as follows:
public String insertString(String s1,String s2,int index){ /** * Implement the insert function of string* The three parameters passed in are: the original string, the string to be inserted, and the insertion position* The returned is the inserted string*/ return s1.substring(0, index) + s2 + s1.substring(index, s1.length()); }2. Add the "Select All" menu to listen to events
Function Description: Trigger this menu to select all text field strings
The editing box in Java actually comes with the function of selecting all. Haha, you can call text.selectAll() directly. It is estimated that there are also ready-made copying and pasting. I almost forgot. After selecting all, you need to determine whether the selected content is empty. If it is not empty, you need to set the "delete" and "cut" buttons to optionally select all codes as follows:
selectAll.addSelectionListener(new SelectionAdapter() { /** * Add the listening event of the "Select All" menu* Function description: Trigger the menu to select all texts in the text field, and set the "Delete" and "Cut" buttons to optional */ public void widgetSelected(SelectionEvent e) { getText().selectAll(); //Click directly to call the built-in function if(getText().getText() !=null){ //If the content is not empty, it means that there is content all selected, so you need to set the "Delete" "Cut" and "Copy" buttons to optional delete.setEnabled(true); //Click cut.setEnabled(true); copy.setEnabled(true); } } });3. Add "Cut" menu monitoring event
Function description: Trigger this menu, realize the cut() method code of the edit box that directly calls the cut() method of the edit box as follows:
cut.addSelectionListener(new SelectionAdapter() { /** * Add the listening event of the "Cut" menu* Function description: Trigger this menu to cut the selected string*/ public void widgetSelected(SelectionEvent e) { getText().cut(); } });4. Add "Paste" menu monitoring event
Function description: Trigger this menu, and implement paste() method code that directly calls the edit box by pasting the clipboard contents is as follows:
paste.addSelectionListener(new SelectionAdapter() { /** * Add the listening event of the "Paste" menu* Function description: Trigger this menu to paste the contents in the clipboard into the edit box*/ public void widgetSelected(SelectionEvent e) { getText().paste(); } });5. Add the "Copy" menu to listen to events
Function description: Trigger this menu, implement the copy() method code that directly calls the edit box by copying the selected contents as follows:
copy.addSelectionListener(new SelectionAdapter() { /** * Add the listening event of the "Cut" menu* Function description: Trigger this menu to cut the selected string*/ public void widgetSelected(SelectionEvent e) { text.copy (); }6. Add the "Undo" menu monitoring event
Function description: Trigger this menu, undo the current operation, undo the algorithm involved in this function is complicated. For the time being, this Notepad does not support the button undo method, but supports right-click undo (the Java Text component comes with it when the right-click undo is not written by me, haha)
7. Add the "Find" menu to listen to events
Function description: Trigger this menu and perform search operation
find.addSelectionListener(new SelectionAdapter() { /** * A dialog box for adding a search function, where you need to click Find, and then a dialog box pops up, enter the relevant content of the search */ public void widgetSelected(SelectionEvent e) { FindWindow fw = new FindWindow(shell,SWT.DIALOG_TRIM); fw.open(); } });4. Add event listening function (3) auxiliary class
In addition to several menu events in the menu bar, you also need to listen to keyboard events. That is, if a keyboard types a text field, the display of the relevant menu will be triggered: Undo, search, find, and find the next place, replace these four menus and set it to optional
1. Listening of text fields
getText().addKeyListener(new KeyAdapter() { /** * Set keyboard listening events* If you have keyboard typing, you need to set the relevant buttons to be visible: undo, search, and find the next place*/ public void keyReleased(KeyEvent e) { if(getText().getText()!=""){//Indicate that there is input find.setEnabled(true); find_next.setEnabled(true); replace.setEnabled(true); }else{ find.setEnabled(false); find_next.setEnabled(false); replace.setEnabled(true); } } });2. Implement the event listening function of the "Font" menu
The code is as follows:
setFont.addSelectionListener(new SelectionAdapter() { /** * Set the listening event of the font*/ public void widgetSelected(SelectionEvent e) { FontDialog fontDialog = new FontDialog(shell, SWT.NONE); Font oldFont = getText().getFont(); if(oldFont != null) { fontDialog.setFontList(oldFont.getFontData()); } FontData fontData = fontDialog.open(); if(fontData == null) { return; } final Display display = Display.getDefault(); Font newFont = new Font(display, fontData); getText().setFont(newFont); if(oldFont != null) { oldFont.dispose(); } } });five. Form Tag Settings
Extract the main function to the test class, parameterize the title of the form of the Notepad, and pass an initial label into the main function: "Unt titled Notepad"
The parameter constructor is defined in the form class Main_Window, and the passed parameters are the title name constructor as follows:
Main_Window(String titleName){ /** * The parameter passed in with parameter construct is the file name*/ this.titleName = titleName; } Note that: The title of the software is: Untitled Notepad When opening a file, the title is the opened file name. When saving the saved file name, the title is the saved file name. When saving the file name is the saved file name. The method of obtaining the file name (not including the path) is:
shlNotepad.setText((new File( fileDir.trim())).getName());//Get the file name (excluding path) to set the title
For simplicity, I have abbreviated it as a sentence code
Set the program icon, put it in the project directory, and you can directly introduce it to use
Thinking: When prompting the user whether to save, you cannot just look at whether the path is empty. You should check whether the keyboard has been pressed, that is, whether there is any change, and whether the content has changed (it may be right-click to delete it directly and has not passed through the keyboard)
6. Definition of the other three Dialog dialog boxes
1. Find dialog box
Also right-click the newly created package new->other->WindowBuilder->SWT Designer->SWT ->Dialog named FindWindow
The results are as follows:
This window is shared here, the search, replacement, and search for the next place. The search content editing box can trigger the button to click. The search content editing box and the replacement box are not empty. The replacement function can be triggered. Here is a list of the search next place and the replacement method body to search next place:
Idea: First get all the strings in the main window, then get the content that needs to be searched, directly call the search string function provided by Java to obtain the starting index, and then add the search content to the length of the string length that is the string that needs to be rendered, then call the rendering function in the main window to render the string and then display it.
The specific code is as follows:
find_next.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { pareStr = Util.shell.getText_1(); //Get the main window text box content true index = pareStr.indexOf(textContent.getText(),index); //Get the position of the search string in the parent string starting from index if(index == -1){ JOptionPane.showMessageDialog(null, "Not found/""+textContent.getText()+"/"","Notepad", JOptionPane.ERROR_MESSAGE); } int end = index+textContent.getText().length();//Get the end position of rendering Util.shell.selectContent(index, end); index = index+textContent.getText().length(); } });The replacement button triggers the event as follows;
replaceBtn.addSelectionListener(new SelectionAdapter() { /** * Replace button event*/ public void widgetSelected(SelectionEvent e) { pareStr = Util.shell.getText_1(); //Get the main window text box content pareStr = pareStr.replaceFirst(textContent.getText(), replaceText.getText()); Util.shell.showText(pareStr); } });2. Establishment of AboutAuthor dialog box
The creation of this dialog box is the same as the search dialog box. Name it AboutAuthor. The specific renderings are as follows:
This dialog box does not involve related algorithms. Add three JLabel tags and enter three sentences.
3. Establishment of Go_to dialog box
I won’t say much about the method of creating a dialog box. The specific renderings are as follows:
The code implementation is as follows:
queding.addSelectionListener(new SelectionAdapter() { /** * Confirm to jump to a certain line*/ public void widgetSelected(SelectionEvent e) { int n = Integer.parseInt(goto_line.getText()); goto_line.setText(""+ n + ""); Util.shell.gotoOneLine(1); } });Call the gotoOneLine() method in the main window
public void gotoOneLine(int row) { getText().setSelection(row); }At this point, the general functions of the entire Notepad have been completed
7. Summary
From the beginning of writing to the final completion, it took about 2-3 days. I learned a lot of related algorithms. Java programming is very convenient. Many methods do not need to be implemented by myself. You can just call them directly. However, Java also has many shortcomings. For example, I used the Java-owned dialog box to close the window. The result was particularly stuck. If you are interested, you can customize the exit dialog box. Just change the included three-choice dialog box to a custom dialog box. At the same time, the previous one was only for learning and did not consider the efficiency of the algorithm. For example, opening a file operation, it only implemented the function, but did not consider the timeliness of the algorithm. The method used in this example is to read the file by line. You can try to open a text document with thousands of lines by yourself, and you can feel the importance of the algorithm. Also, upward search has not been implemented. The preliminary idea is: find the coordinates that need to be found, and then start to go back from the position of the coordinates you are looking for, and invert the search content, and then call the string search function that comes with Java.
For example:
The parent string is "ab notepad def3g". You need to start from the "3" string to look up the "notepad" string forward. You can completely invert the string "ab notepad def" before the position of the "3" string in the parent string to "g3fed" and invert the search content to "power notation". Then call the string search function included in Java to find the location, and then restore it.
The above are the detailed steps to write notepad step by step. Java writes desktop notepad applications based on SWT plug-in, hoping that it will be helpful to everyone's learning.