Once again fickering.
Hi friends,
I just wan to study how can we create custom components with heavy graphical drawing on it. And how can
we write better program to make it flicker free.
The code below creates custome Label with some drawing on it. This component is then added on a frame, and can
be dragged on the screen by mouse,
You can notice considerable flickering while dragging.
Can anybody explain me how can we use the concept of double buffering or page flipping for this perticular component. ?
Here is the code
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.event.*;
publicclass Testextends JFrame
{
private DraggabledLabel l =new DraggabledLabel();
public Test()
{
getContentPane().setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(l);
setSize(400, 400);
setVisible(true);
}
publicstaticvoid main(String[] args)
{
new Test();
}
class DraggabledLabelextends JLabelimplements MouseListener, MouseMotionListener
{
private Point mousePressedPoint =new Point();
public DraggabledLabel()
{
setSize(getPreferredSize());
setLocation(50, 50);
setBorder(BorderFactory.createEtchedBorder());
addMouseListener(this);
addMouseMotionListener(this);
}
publicvoid mouseClicked(MouseEvent e){}
publicvoid mouseEntered(MouseEvent e){}
publicvoid mouseExited(MouseEvent e){}
publicvoid mousePressed(MouseEvent e)
{
mousePressedPoint = e.getPoint();
}
publicvoid mouseReleased(MouseEvent e){}
publicvoid mouseDragged(MouseEvent e)
{
Point p = SwingUtilities.convertPoint(this, e.getPoint(), getParent());
setLocation(p.x - mousePressedPoint.x, p.y - mousePressedPoint.y);
}
publicvoid mouseMoved(MouseEvent e){}
BufferedImage bi;
private BufferedImage getImage()
{
if (bi ==null)
{
bi = (BufferedImage) createImage(getWidth(), getHeight());
Graphics biGraphics = bi.createGraphics();
biGraphics.setColor(getGraphics().getColor());
super.paintComponent(biGraphics);
int i = 5;
int size = getWidth();
while( size > 0 )
{
size = size = getWidth() - i * 2 - 1;
biGraphics.drawRect(i, i, size, size);
i = i + 2;
}
}
return bi;
}
protectedvoid paintComponent(Graphics g)
{
bi = getImage();
g.drawImage(bi, 0 , 0,null);
}
public Dimension getPreferredSize()
{
returnnew Dimension(200, 200);
}
}
}

