我正在制作编辑器。我正在使用以下代码将 html 文档从路径添加到 texteditor。
try {
filename="filepath";
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filename));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
result = fileData.toString();
jtextpane.setContentType("text/html");
jtextpane.setText(result);
} catch (Exception ex) {
jtextpane.setText(".,1..."+ex.toString());
}
直到我第一次不使用这个文件加载时,我的编辑器工作正常。但是添加此代码后,我的粘贴按钮无法正常工作。它正在新行中粘贴。当我在那种情况下删除 "SETCONTENTTYPE" 时,粘贴工作正常。但我无法删除它。我必须将 html 文件加载到编辑器中。请帮忙。 提前谢谢你。
最佳答案
如果您想在您的文本编辑器中“打开”html 文档,您应该使用 JEditorPane 组合(如果有必要)和 JScrollPane。这是一个示例代码(它需要 try/catch block ):
private void visualiserLog() {
JEditorPane docEP = new JEditorPane();
docEP.setEditable(true);
File f = new File(/path/to/file.html);
java.net.URL fileURL = null;
try {
fileURL = f.toURI().toURL(); // Transform path into URL
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
docEP.setPage(fileURL); // Load the file to the editor
}
catch (IOException e) {
e.printStackTrace();
}
// Initialize scroll pane (if you need it)
JScrollPane docSP = new JScrollPane(docEP,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
docSP.setPreferredSize(new Dimension(800,700));
// Set up a frame to layout the editor panel
JFrame frame = new JFrame("HTML File");
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setBounds(0,0,800,700);
// If you don't use ScrollPane, you must swap docSP for docEP
frame.getContentPane().add(docSP,BorderLayout.CENTER);
frame.setVisible(true);
}
我认为将文件设置到编辑器中可以正常工作。之后你应该放置复制函数和必要的监听器。
问候!
关于java - 将 html 文档加载到 JTextPane 使我的编辑器在粘贴时表现非常糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6660150/