First off I am a novice programmer. I am write a code that accesses a directory and searches for .png files created on a specific day as defined in a GUI. It then creates a filelist of those files. Then it takes the files and opens them rotates them if the user has selected that radio buttons, resizes them, adds a tab to a tabbed pane, and displays the image in a label on that tab in the tabbed pane. I am getting the error OutOfMemoryError: Java heap space after it loads only a few of the images. I am making the buffer image size so large because if I dont the image quality looks terrible after I resize it.
What is happening is it isn't clearing the buffered images after each loop.
for (File file : filelist){
if (file.getName().contains(jTextField2.getText() + jTextField1.getText())) {
System.out.println(file.getAbsolutePath().toString());
label[i] = rotateAndResize(file, i);
addTabs(i);
i = i + 1;
}
}
public JLabel rotateAndResize(File file, int i) {
BufferedImage img;
BufferedImage buffer;
int imgx = 0;
int imgy = 0;
img = null;
try {
img = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(DailyViewView.class.getName()).log(Level.SEVERE, null, ex);
}
if (jRadioButton16.isSelected()){
imgx = jTabbedPane1.getHeight()*2;
imgy = jTabbedPane1.getWidth()*2;
} else {
imgx = jTabbedPane1.getWidth()*2;
imgy = jTabbedPane1.getHeight()*2;
}
buffer = new BufferedImage(imgx*2,imgy*2, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = buffer.createGraphics();
AffineTransform at = g.getTransform();
int xRot = imgx/2;
int yRot = imgy/2;
if (jRadioButton16.isSelected()) {
at.rotate(-1*(Math.PI/2), xRot, yRot);
at.translate(imgx/8, imgy/16*7);
} else {
at.translate(imgx/2,0);
}
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.transform(at);
g.drawImage(img, 0, 0, imgx, imgy, null);
if (jRadioButton16.isSelected()) {
ImageIcon finalImage = new ImageIcon(buffer.getScaledInstance((int) (imgx),(int) (imgy), Image.SCALE_AREA_AVERAGING));
label[i] = new JLabel(finalImage);
finalImage = null;
} else {
ImageIcon finalImage = new ImageIcon(buffer.getScaledInstance((int) (imgx),(int) (imgy*1.125), Image.SCALE_AREA_AVERAGING));
label[i] = new JLabel(finalImage);
finalImage = null;
}
buffer.flush();
img.flush();
buffer = null;
img = null;
g.dispose();
g.finalize();
System.gc();
return label[i];
}
publicvoid addTabs (int i){
panel[i] = new JPanel();
jTabbedPane1.addTab("Panel "+ i, panel[i]);
panel[i].setLocation(0, 0);
panel[i].add(label[i]);
}