How can I deal with this weird effect when scrolling using the JScrollArea:

The code:
import java.util.*;
import java.util.prefs.BackingStoreException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;
public class Main extends JFrame implements ActionListener, AdjustmentListener{
CustomComponent cc;
JScrollPane jsp;
public static void main(String[] args) {
Main m = new Main();
}
public Main(){
setTitle( "Diverse Testari 7");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
cc = new CustomComponent();
cc.setImage("rgbcmy.jpg");
jsp = new JScrollPane( cc,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
jsp.setPreferredSize( new Dimension( getWidth(), getHeight() ) );
jsp.setOpaque( true );
jsp.setBackground( Color.DARK_GRAY );
jsp.getVerticalScrollBar().addAdjustmentListener(this);
jsp.getHorizontalScrollBar().addAdjustmentListener(this);
setBackground( Color.red );
add( jsp );
setVisible( true );
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("EVENT: " + e.toString() );
}
@Override
public void adjustmentValueChanged(AdjustmentEvent arg0) {
// TODO Auto-generated method stub
}
}
class CustomComponent extends JPanel{
BufferedImage img = null;
public void setImage( String str ){
try {
img = ImageIO.read( new File( str ) );
System.out.println(img.getColorModel().toString());
System.out.println("SUCCESS!");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
// TODO Auto-generated method stub
return new Dimension(img.getWidth(), img.getHeight() );
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setClip(100, 100, 100, 100);
System.out.println("paintComponent");
if( img != null )
{
System.out.println("Obs: Imagine existenta!");
g2d.drawImage(img, null, 0,0);
}
else
{
System.out.println("Eroare: nu este imaginea!");
}
}//*/
}
this is common issue where
paint code isn't optimized, part of side effect is possible to removing by disable flickering, have to set additonal parameters forJViewports ScrollModeand by notifying by
super.paintComponent(g);too+1 for Óscar Gómez Alcañiz