Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

ScrollPane and BufferedImage wierdness - image scrolls back scrambled

843806Oct 3 2007 — edited Oct 3 2007
Hi,

I've created a terribly simple application that reads in a jpg into a buffered image, uses a JPanel to draw it and places it all in a ScrollPane. The source is below. If one scrolls by dragging the scrollBar so that some of the image goes off screen, then when it is brought back either you get no image or a smear of black. Same result for a wide variety of images and the same problem exists on Linux, Mac, and PC (albeit on a Mac). Any pointers would be appreciated.

I need to keep the BufferedImage because I will be doing a fair amount of modification to the image.

The code is below - replace "simple.jpg" by any image you have laying around.

Thanks!

Dave

/*
* Main.java
*
* Created on October 3, 2007, 10:07 AM
*
* This is the simplest program that I can make exhibit the behavior. Run the program so that it opens
* simple.jpg. This is a jpg created from a PDF, but the problem exists for any jpg.
*/

package graphicstutorial1;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;

public class Main {

public static void main(String[] args) {
SimpleFrame sf = new SimpleFrame();
sf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sf.setVisible(true);
}
}

class SimpleFrame extends JFrame {
public SimpleFrame() {

Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;

setSize(screenWidth/2, screenHeight/2);
setLocation(screenWidth/4,screenHeight/4);

setTitle("Scroll fails if you drag the thumbwheel back and forth");

try {
BufferedImage image = ImageIO.read(new File("simple.jpg"));
MyPanel panel = new MyPanel(image);
JScrollPane jsp = new JScrollPane(panel);
this.getContentPane().add(jsp);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}

class MyPanel extends JPanel {

private BufferedImage image;


public MyPanel(BufferedImage img) {
super();
this.image = img;

}
public void paintComponent(Graphics g) {
super.paintComponent(g); // take care of background, etc.
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image,0,0,null);
}


public Dimension getSize() {
return new Dimension(image.getWidth(),image.getHeight());
}

public Dimension getPreferredSize() {
return new Dimension(image.getWidth(),image.getHeight());
}

public int getWidth() {
return image.getWidth();
}

public int getHeight() {
return image.getHeight();
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 31 2007
Added on Oct 3 2007
7 comments
161 views