我正在创建一个文本编辑器作为一个侧面项目,到目前为止,我正在努力保存和加载文本的字体字母,颜色和装饰;换句话说,我只能保存纯文本。我的问题是,如何保存和加载所有这些?
private void Edit() {//This is the method where the program edits the text
StyledDocument doc = this.tpText.getStyledDocument();
Style estilo = this.tpText.addStyle("miEstilo", null);
StyleConstants.setForeground(estilo, colour); //Color
StyleConstants.setFontFamily(estilo, fontLetter);//Letter
StyleConstants.setFontSize(estilo, size);//Size
StyleConstants.setBold(estilo, bold);//Bold
StyleConstants.setItalic(estilo, italics);//Italics
StyleConstants.setUnderline(estilo, underline);//Underline
doc.setCharacterAttributes(this.tpText.getSelectionStart(), this.tpText.getSelectionEnd() - this.tpText.getSelectionStart(), this.tpText.getStyle("miEstilo"), true);//The only text that will be edited is the one that the user highlights
}
private void comboxFontsActionPerformed(java.awt.event.ActionEvent evt) {//This is one of the methods in which the program edits the text
this.fontLetter = (String) this.comboxFonts.getSelectedItem();
Edit();
}
private void mibtnSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//Save as... menu item button
int saveResult = fileSelect.showSaveDialog(null);
if (saveResult == fileSelect.APPROVE_OPTION) {
saveFile(fileSelect.getSelectedFile(), this.tpText.getText());
this.mibtnSave.setEnabled(true);
}
}
public void saveFile(File file, String contents) {//Save File
BufferedWriter writer = null;
String filePath = file.getPath();
try {
writer = new BufferedWriter(new FileWriter(filePath));
writer.write(contents);
writer.close();
this.tpText.setText(contents);
currentFile = file;
} catch (Exception e) {
}
}
public void openFile(File file) {//Load File
if (file.canRead()) {
String filePath = file.getPath();
String fileContents = "";
if (filePath.endsWith(".txt")) {
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()) {
fileContents += sc.nextLine();
}
sc.close();
} catch (FileNotFoundException e) {
}
this.tpText.setText(fileContents);
currentFile = file;
} else {
JOptionPane.showMessageDialog(null, "Only .txt files are supported.");
}
} else {
JOptionPane.showMessageDialog(null, "Could not open file...");
}
}
答案 0 :(得分:0)
我不知道我的问题是否正确,但如果您尝试保存除纯文本之外的样式,您可以执行以下操作。
将所有样式属性保存在文本文件旁边的另一个文件中,您可以在打开文本文件时将其恢复。