I'm trying to append a text of a file into my JTextPane. This works great for files that are under 10Mb but for size above it (and I checked ~50Mb) I get the notorious exception 'OutOfMemoryError: Java heap space'.
I'm trying to understand why do I get java heap memory if both methods are static and there's no 'new' in every iteration under the while(line!=null). If I can open the file in a regular txt editor, why does this code fail to execute?
The code looks like this:
public static void appendFileData(JTextPane tPane, File file) throws Exception
{
try{
//read file's data
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
try{
while (line != null)
{
JTextPaneUtil.appendToConsole(tPane, "\n"+line,Color.WHITE, "Verdana", 14);
line = br.readLine();
}
}finally
{
br.close();
}
}catch(Exception exp)
{
throw exp;
}
}
the appendToConsole is:
public static void appendToConsole(JTextPane console, String userText, Color color, String fontName, int fontSize)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, fontName);
aset = sc.addAttribute(aset, StyleConstants.FontSize, fontSize);
aset = sc.addAttribute(aset,StyleConstants.Alignment, StyleConstants.ALIGN_CENTER);
int len = console.getDocument().getLength();
console.setCaretPosition(len);
console.setCharacterAttributes(aset, false);
console.replaceSelection(userText);
}
Why are you adding attributes for every line? Swing needs to do a lot of work to either keep track of all those attributes, or merge them into one attribute for the entire file.
Try using code like the following AFTER you have loaded all the data into the text pane to set the attributes for the entire text pane at one time.
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);
Also, I don't think you need to set the font by using attributes. You should just be able to use:
textPane.setFont(...);