Hello,
I'm new to this
Java thing, so if I'm being obtuse, that why! I'm trying to write an application that scolls text horizontally, and cobbled together the first bit of code below . .it works OK, but the text does flicker slightly. I heard taht using double buffering should solve the problem, so added some code to handle this - see code sample 2. The problem is that the flicker is far worse when buffering is used, and the bigger the window, the worse it gets. Does anyone have any ideas at all?
Code Sample 1: (no buffering)
import java.awt.*;
import java.util.*;
import java.awt.image.*;
public class AnimText extends Frame
{
private static int DELAY = 100;
int possy = 0;
Insets insets;
public void paint(Graphics g)
{
if (insets == null)
{
insets = getInsets();
}
int x = insets.left;
int y = insets.top;
int width = getWidth() - insets.left - insets.right;
int height = getHeight() - insets.top - insets.bottom;
String subject = "moving.... text is here";
char text[] = subject.toCharArray();
g.setFont(new Font("Serif", Font.PLAIN, 18));
//g.setColor(Color.white);
//g.fillRect(x, y, width, height);
//bufferG.drawChars(text, 0, 23, x + possy-1, y + 30);
g.setColor(Color.red);
g.drawChars(text, 0, 23, x + possy, y + 30);
}
public void go()
{
TimerTask task = new TimerTask()
{
public void run()
{
possy++;
if (possy >= getWidth())
{
possy = 0;
}
repaint();
}
};
Timer timer = new Timer();
timer.schedule(task, 0, DELAY);
}
public static void main(String args[])
{
AnimText f = new AnimText();
f.setSize(200, 200);
f.show();
f.go();
}
}
Code Sampel 2: With Buffering
import java.awt.*;
import java.util.*;
import java.awt.image.*;
public class AnimTextBuffer extends Frame
{
private static int DELAY = 100;
int possy = 0;
Insets insets;
Image buffer;
Dimension oldSize;
public void paint(Graphics g)
{
//super.paint(g);
if ((oldSize == null) || (oldSize != getSize()))
{
oldSize = getSize();
buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
}
if (insets == null)
{
insets = getInsets();
}
int x = insets.left;
int y = insets.top;
int width = getWidth() - insets.left - insets.right;
int height = getHeight() - insets.top - insets.bottom;
String subject = "moving.... text is here";
char text[] = subject.toCharArray();
Graphics bufferG = buffer.getGraphics();
bufferG.setColor(Color.white);
bufferG.fillRect(x, y, width, height);
bufferG.setFont(new Font("Serif", Font.PLAIN, 18));
bufferG.setColor(Color.red);
bufferG.drawChars(text, 0, 23, x + possy, y + 30);
g.drawImage(buffer, 0, 0, this);
}
public void go()
{
TimerTask task = new TimerTask()
{
public void run()
{
possy++;
if (possy >= getWidth())
{
possy = 0;
}
repaint();
}
};
Timer timer = new Timer();
timer.schedule(task, 0, DELAY);
}
public static void main(String args[])
{
AnimTextBuffer f = new AnimTextBuffer();
f.setSize(200, 200);
f.show();
f.go();
}
}