Here is another example.
It uses double buffering.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.Font;
import java.util.ArrayList;
public class Text extends JPanel {
static final int CHAR_WIDTH = 7;
static final int CHAR_HEIGHT = 14;
public static void main(String[] args) {
JFrame frame = new JFrame();
Text text = new Text();
frame.add(text);
text.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
text.runningText("This is a running text. Words that don't fit completely on a line will automatically be moved to the next line.", 30, 30, 15, 100);
}
private void runningText(String str, int x, int y, int maxWidth, int delay) {
new Thread() {
@Override
public void run() {
String[] lines = toLines(str, maxWidth);
int maxLineLength = maxLength(lines);
Graphics2D g = image.createGraphics();
g.setFont(new Font("monospaced", Font.PLAIN, 12));
g.setColor(Color.BLACK);
g.drawRect(x-5, y-5, maxWidth*CHAR_WIDTH + 10, lines.length*CHAR_HEIGHT + 10);
for(int j = 1; j < str.length(); j++) {
g.setColor(Color.WHITE);
g.fillRect(x, y, maxLineLength*CHAR_WIDTH, lines.length*CHAR_HEIGHT);
g.setColor(Color.BLACK);
int count = 0;
loop:
for(int i = 0; i < lines.length; i++) {
for(int k = 0; k < lines[i].length(); k++) {
g.drawString(lines[i].substring(k, k+1), x+k*CHAR_WIDTH, y+(i+1)*CHAR_HEIGHT);
count++;
if(count == j) break loop;
}
}
repaint();
try {
Thread.sleep(delay);
} catch(Exception e) {
}
}
g.dispose();
}
}.start();
}
BufferedImage image = null;
public Text() {
initImage();
}
public void initImage() {
int w = getWidth();
int h = getHeight();
if(w <= 0 || h <= 0) {
w = 800;
h = 600;
}
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
g.dispose();
}
@Override
public void setPreferredSize(Dimension d) {
super.setPreferredSize(d);
initImage();
}
static String[] toLines(String str, int maxLength) {
ArrayList<String> lines = new ArrayList<>();
String[] words = str.split("\\s");
String line = "";
int length = 0;
for(String word: words) {
if(length+word.length()+1 > maxLength) {
lines.add(line);
line = "";
length = 0;
}
if(length > 0) {
line += " ";
length += 1;
}
line += word;
length += word.length();
}
if(line.length() > 0) lines.add(line);
return lines.toArray(new String[lines.size()]);
}
static int maxLength(String[] lines) {
int length = 0;
for(String line: lines) length = Math.max(length, line.length());
return length;
}
@Override
public void paint(Graphics _g) {
Graphics2D g = (Graphics2D)_g;
g.scale(3,3);
g.drawImage(image, 0, 0, null);
}
}