盾怪网教程:是一个免费提供流行杀毒软件教程、在线学习分享的学习平台!

JBuilder 9 开发一个文本编辑器

时间:2024/10/8作者:未知来源:盾怪网教程人气:

[摘要]Open menu item.   if (!okToAbandon())   return;      // Use the OPEN version of the dialog, test r...
Open menu item.
  if (!okToAbandon()) {
  return;
  }
  // Use the OPEN version of the dialog, test return for Approve/Cancel
  if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) {
  // Call openFile to attempt to load the text from file into
  TextArea
  openFile(jFileChooser1.getSelectedFile().getPath());
  }
  this.repaint();
  }

   添加从文件中读出文字的代码

  添加从选定的文件中将文字实际读到文本区JTextArea的代码。

  首先需要在用户类中增加一个新的方法执行实际打开文件的操作,这个方法叫作openFile()。

  // Open named file; read text from file into jTextArea1; report to statusBar.
  void openFile(String fileName)
  {
  try
  {
  // Open a file of the given name.
  File file = new File(fileName);
  // Get the size of the opened file.
  int size = (int)file.length();
  // Set to zero a counter for counting the number of
  // characters that have been read from the file.
  int chars_read = 0;
  // Create an input reader based on the file, so we can read its data.
  // FileReader handles international character encoding conversions.
  FileReader in = new FileReader(file);
  // Create a character array of the size of the file,
  // to use as a data buffer, into which we will read
  // the text data.
  char[] data = new char[size];
  // Read all available characters into the buffer.
  while(in.ready()) {
   // Increment the count for each character read,
   // and accumulate them in the data buffer.
   chars_read += in.read(data, chars_read, size - chars_read);
  }
  in.close();
  // Create a temporary string containing the data,
  // and set the string into the JTextArea.
  jTextArea1.setText(new String(data, 0, chars_read));
  // Display the name of the opened directory+file in the statusBar.
  statusBar.setText("Opened "+fileName);
  }
  catch (IOException e)
  {
  statusBar.setText("Error opening "+fileName);
  }
  }

  替换先前所说的File

关键词:JBuilder 9 开发一个文本编辑器




Copyright © 2012-2018 盾怪网教程(http://www.dunguai.com) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版