我已经使用 JTextPane 和 AdvancedRTFEditorKit 在 java/swing 中创建了一个编辑器,我从这里找到了它(使用它而不是 RTFEditorKit,因为它已经过时了),但是如果你可以说这是一个问题,我有一个“问题” ,使用 AdvancedRTFEditorKit 我只能打开我用它创建的文件,例如我无法打开 .txt、.java、.cpp、.c,我只能打开我使用编辑器创建的文件。所以是正常吗?或者我做错了什么?还有其他人使用 AdvancedRTFEditorKit 吗?
谢谢大家,很高兴很快看到答案!
我用过这个 RTF 编辑器工具包:点击这里!
这是SSCCE...
package sscceeditor;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.text.BadLocationException;
import rtf.AdvancedRTFDocument;
import rtf.AdvancedRTFEditorKit;
class ExampleFrame extends JFrame{
private JMenuBar bar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadItem = new JMenuItem("Load");
private JTextPane txtPane = new JTextPane(new AdvancedRTFDocument());;
private JScrollPane scroller = new JScrollPane(txtPane);
private JFileChooser chooser = new JFileChooser();
private AdvancedRTFEditorKit rtfKit = new AdvancedRTFEditorKit();
//ctor begins...
public ExampleFrame(){
super("Example Editor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 400);
this.setLocationRelativeTo(null);
saveItem.addActionListener(new SaveHandler());
loadItem.addActionListener(new LoadHandler());
//set the kit...
txtPane.setEditorKit(rtfKit);
//create the menu...
fileMenu.add(saveItem);
fileMenu.add(loadItem);
bar.add(fileMenu);
this.setJMenuBar(bar);
//create the main panel...
JPanel mainPane = new JPanel();
mainPane.setLayout(new BorderLayout());
mainPane.add(BorderLayout.CENTER , scroller);
this.setContentPane(mainPane);
}//end of ctor.
//inner event handler classes...
class SaveHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showSaveDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
try(BufferedWriter bw = new BufferedWriter(
new FileWriter(chooser.getSelectedFile().getPath())))
{
txtPane.setText("");
rtfKit.write(bw, txtPane.getDocument() , 0 , txtPane.getDocument().getLength());
bw.close();
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
class LoadHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showOpenDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
try(BufferedReader bw = new BufferedReader(
new FileReader(chooser.getSelectedFile().getPath())))
{
txtPane.setText("");
rtfKit.read(bw, txtPane.getDocument() , 0 );
bw.close();
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
}//end of class ExampleFrame.
public class SSCCEeditor {
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new ExampleFrame().setVisible(true);
}
});
}
}