实现一个文本滚动,可是文本是从左向右滚动的,怎么让它从右向左滚动呢?还有怎样解决文字滚动时闪动的问题,看到有些人说用双缓冲,可是不知道怎么做?
源码如下:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;import javax.swing.*;public class MovingTextIcon implements Icon, Runnable {
private JLabel renderer = new JLabel(); private int width;
private int height; private int curPos = 180;
private Component component = null;
private Thread thread = null; public MovingTextIcon(String text, int width, int height) { this.renderer.setText(text);
this.renderer.setSize(this.renderer.getPreferredSize());
this.width = width;
this.height = height; } public void paintIcon(Component c, Graphics g, int x, int y) {
this.component = c; g = g.create();
g.setClip(0, 0, width, height);
g.translate(x + curPos, y + (height - renderer.getHeight()) / 2); renderer.paint(g);
if (curPos + renderer.getWidth() > width) {
g.translate( -width, 0); } g = g.create();
renderer.paint(g); g.dispose();
if (thread == null || !thread.isAlive()) {
thread = new Thread(this);
thread.start();
}
} public int getIconWidth() {
return width;
} public int getIconHeight() {
return height;
} public void run() {
while (true) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
}
if (!component.isVisible() || !component.isDisplayable()) {
break;
}
curPos += 3;
if (curPos >= width) {
curPos = 0;
}
component.repaint();
component.setForeground(Color.white);
}
}
}
源码如下:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;import javax.swing.*;public class MovingTextIcon implements Icon, Runnable {
private JLabel renderer = new JLabel(); private int width;
private int height; private int curPos = 180;
private Component component = null;
private Thread thread = null; public MovingTextIcon(String text, int width, int height) { this.renderer.setText(text);
this.renderer.setSize(this.renderer.getPreferredSize());
this.width = width;
this.height = height; } public void paintIcon(Component c, Graphics g, int x, int y) {
this.component = c; g = g.create();
g.setClip(0, 0, width, height);
g.translate(x + curPos, y + (height - renderer.getHeight()) / 2); renderer.paint(g);
if (curPos + renderer.getWidth() > width) {
g.translate( -width, 0); } g = g.create();
renderer.paint(g); g.dispose();
if (thread == null || !thread.isAlive()) {
thread = new Thread(this);
thread.start();
}
} public int getIconWidth() {
return width;
} public int getIconHeight() {
return height;
} public void run() {
while (true) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
}
if (!component.isVisible() || !component.isDisplayable()) {
break;
}
curPos += 3;
if (curPos >= width) {
curPos = 0;
}
component.repaint();
component.setForeground(Color.white);
}
}
}
我觉得不是文字方向的问题,应该是paint的的问题吧