Teach you to write text editor of 4 with JAVA

  • 2021-12-12 04:20:49
  • OfStack

In fact, writing here, I have almost died. . .

Conventional routine, here is the portal of the first three articles. Students who need it can see 1: JAVA writing text editor (3) JAVA writing text editor (2) JAVA writing text editor (1)

Now we are only short of the last part, so we must finish it before we die!

Let's analyze 1 again. The last Menu has several buttons. I don't know if you have found it. Two of them are very simple, one is new and one is exit. New we instantiate 1 under the parent window can, but here there is bug, close any 1 child window will follow the parent window closed. The other one is exit, just dispose (). Process 1 in the listener:

You don't need to post too much context code here, just find the main window.java and find this function


@Override
 public void actionPerformed(ActionEvent e) {
  if (e.getSource() == item_about) {
   new about_Window();
  }else if (e.getSource() == item_word_format) {
   new about_Format();
  }else if (e.getSource() == item_new) {
   new test5(); //  Select New  new1 New windows   , there are bug Closing any child window will be followed by closing the parent window 
  }else if (e.getSource() == item_exit) {
   this.dispose();
  }
 }

Write text editor in JAVA (1) We have analyzed, there is a good package of tools JFileChooser can be called directly.

In fact, after digesting this component introduction in hyperlinks, there is no problem in accessing files. Next, we add a listener, and the corresponding method is added to the listener:

Of course, you must first declare JFileChooser in the class


@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == item_about) {
			new about_Window();
		}else if (e.getSource() == item_word_format) {
			new about_Format();
		}else if (e.getSource() == item_new) {
			new test5(); //  Select New  new1 New windows   , there are bug Closing any child window will be followed by closing the parent window 
		}else if (e.getSource() == item_exit) {
			this.dispose();
		}else if (e.getSource() == item_open) {
			openFile();
		}else if (e.getSource() == item_save) {
			saveFile();
		}
	}

SaveFile method:


private void saveFile() {
		File file = null;
		int result ;
		fileChooser = new JFileChooser("C:\\");
		fileChooser.setApproveButtonToolTipText(" Save "); //  Set the real text of the confirmation button 
		fileChooser.setDialogTitle(" Save a file "); //  Settings title
		result = fileChooser.showOpenDialog(rootPane); //  Settings Dialog Root of View  Root layout 
		
		//--------------------------------------------------------------------------
		if(result == JFileChooser.APPROVE_OPTION) {
			file = fileChooser.getSelectedFile(); //  If the OK button is clicked, give file Fill in the file path 
		}
		
		//--------------------------------------------------------------------------
		/*FileOutputStream fileOutputStream = null; //  Documents io Class 
		if (file != null) {
			try {
				fileOutputStream = new FileOutputStream(file); 
			}catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			
			String content = edit_text_area.getText();
			
			try {
				fileOutputStream.write(content.getBytes());
			}catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					if (fileOutputStream!=null) {
						fileOutputStream.close();
					}
				}catch (IOException e) {
					e.printStackTrace();
				}
			}
		}*/
		//--------------- There are serious bug No problem for writing characters to files, but there will be garbled codes when reading Chinese characters -----------
		//--------------------------------------------------------------------------
		
		try{
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); //  Encoding and converting characters 
			BufferedWriter writer = new BufferedWriter(write);
			String content = edit_text_area.getText();
			writer.write(content);
			writer.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		
	}

OpenFile method:


/**
	 *  Click New Press item Hour   Open JFileChooser Dialog box 
	 *  And process file reading 
	 */
	private void openFile() {
		File file = null;
		int result ;
		fileChooser = new JFileChooser("C:\\");
		fileChooser.setApproveButtonToolTipText(" Determine "); //  Set the real text of the confirmation button 
		fileChooser.setDialogTitle(" Open a file "); //  Settings title
		result = fileChooser.showOpenDialog(rootPane); //  Settings Dialog Root of View  Root layout 
		
		//--------------------------------------------------------------------------
		if(result == JFileChooser.APPROVE_OPTION) {
			file = fileChooser.getSelectedFile(); //  If the OK button is clicked, give file Fill in the file path 
		}
		
		//--------------------------------------------------------------------------
		//-------------------- The following processes the file and loads the contents into the parent form's textarea Medium --------------------
		/*FileInputStream fileInputStream = null;
		if (file != null) {
			try { // Note the null pointer exception here   That is, when the file is not found, it needs to be processed 
				fileInputStream = new FileInputStream(file); //  Will file The data stream of the file is loaded into the fileInputStream Li 
			}catch (FileNotFoundException e) {  //  Exception caught   , needs to be processed 
				e.printStackTrace(); //  Instantiate the exception as e  Then in the console Console  Print out the location and cause of the error 
				TipDialog tmpDialog = new TipDialog(this," Error file ",true," Wrong folder name, please check again !");//  Here we can also check 1 Field work 1 Some processing, pop up here 1 Alert dialog box 
				
			}
			
			// Read a file 
			int readbyte ;
			try {
				while ((readbyte = fileInputStream.read())!=-1) { //1 Read file of segment 
					edit_text_area.append(String.valueOf((char)readbyte)); // In editarea  Li 1 Row addition 
				}
			}catch (IOException e) { //  Handle exceptions 
				e.printStackTrace();
			}finally {
				try {
					if (fileInputStream != null) { // Right fileInputStream  Recycle 
						fileInputStream.close();
					}
				}catch (IOException e) { // Throw an exception 
					e.printStackTrace();
				}
			}
		}*/
		//--------------- There are serious bug For reading Chinese characters, there will be garbled codes -------------------------------
		//--------------------------------------------------------------------------
		
		if(file.isFile() && file.exists()) {
			BufferedReader reader = null;
			try {
				InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
				reader = new BufferedReader(inputStreamReader);
				
				String readLine = "";
				while ((readLine = reader.readLine()) != null) { //  Right BufferedReader Data 1 Line reading 
					//edit_text_area.append(readLine);  Writing this way will show that all sentences appear in the same 1 Line situation, so every time append Add it at the back when 1 Newline character 
					edit_text_area.append(readLine+'\n');  // Right edit_text_area 1 Line plus 
				}
				
				reader.close(); //  Shut down reader
				
			}catch (IOException e) {
				e.printStackTrace();
				//TipDialog tmpDialog = new TipDialog(this," Error file ",true," Wrong folder name, please check again !");
			}
			
			
		}
	}

In fact, the two methods here are very similar. The path of the selected file can be obtained through FileChooser, and then the path can be obtained through File, and the normal file read and write operation is performed under 1. Note 1 Be sure to handle IO operation exceptions.

If you pay attention, you can see that in fact, my IO has 1 operation commented out, and the commented part is read and write according to the JFileChooser component. However, after testing, it is found that there is no code for Chinese characters, so it is garbled to read after saving. Therefore, another writing method is adopted.

At this point, the whole text editor has been completed. Some students may seem to feel confused, so I will upload the source code in the blog, and students who need it can download it directly. JAVA writing text editor source code

Summarize


Related articles: