Java Swing将文件加载到JEditorPane中 [英] Java Swing load file into JEditorPane
问题描述
我正在尝试用Java/Swing编写文本编辑器类型的应用程序.我有FileChooser,并且可以将文件内容打印到控制台.我想将文件加载到JEditorPane
I'm trying to write text-editor type application in Java/Swing. I have the FileChooser working and I can print out the contents of the file to the console. I want to load the file into a JEditorPane
当我调用setText()时,它将更新文本的值(我可以打印getText的结果,但实际的EditorPane不会刷新).我尝试在封装JScrollPane的JEditorPane上调用repaint/revalidate,但是没有什么可以将文本刷新为我发送给setText的内容.
When I call setText(), it updates the value of the text (I can print the result of getText, but the actual EditorPane is not refreshing). I've tried calling repaint/revalidate on the JEditorPane, the encapsulating JScrollPane but nothing will refresh the text to what I sent to setText.
我想念什么吗?
P.S. JEditorPane包装在JScrollPane中,我的mainEditor中有一个将字符串传递给JEditorPane的setText方法的方法.
P.S. The JEditorPane is wrapped inside a JScrollPane, and I have a method in my mainEditor that passes the string to the setText method of the JEditorPane.
if (r == JFileChooser.APPROVE_OPTION)
{
FileInputStream fis;
BufferedReader br;
try
{
fis = new FileInputStream(
chooser.getSelectedFile() ) ;
br = new BufferedReader(
new InputStreamReader( fis ) ) ;
String read ;
StringBuffer text = new StringBuffer() ;
while( ( read = br.readLine() ) != null )
{
text.append( read ).append( "\n" ) ;
}
Main.frame.mainEditor.setText( text.toString() ) ;
Main.frame.mainEditor.revalidate();
}
catch( IOException e1 )
{
JOptionPane.showMessageDialog( this ,
"Error in File Operation" ,
"Error in File Operation" ,
JOptionPane.INFORMATION_MESSAGE) ;
}
}
推荐答案
将String
形成为File
引用,将其转换为URL
,然后调用
Form the String
into a File
reference, convert that to an URL
then call setPage(URL)
.
有关示例,请参见此处.
这篇关于Java Swing将文件加载到JEditorPane中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!