该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
写了个简单的例子给你:
public class TextChangePane extends JComponent implements ActionListener {
private static final int CYCLE_TIME = 10000;
private long startTime = 0;
private long nowTime = 0;
private float move = 0.0001f;
private Timer timer;
private String text = "一二三四五六七八九零";
private Color startColor = Color.RED;
private Color endColor = Color.BLUE;
public TextChangePane() {
timer = new Timer(30, this);
timer.setInitialDelay(1000);
startTime = 1000 + System.nanoTime() / 1000000;
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
float[] fractions = {0.f, move, move + 0.0001f, 1.f};
Color[] colors = {startColor, startColor, endColor, endColor};
FontMetrics metrics = g.getFontMetrics();
int length = metrics.stringWidth(text);
LinearGradientPaint paint = new LinearGradientPaint(0, 0, length, 0, fractions, colors);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(paint);
g2d.drawString(text, 0, 20);
}
@Override
public void actionPerformed(ActionEvent e) {
nowTime = System.nanoTime() / 1000000;
long moveTime = nowTime - startTime;
if (moveTime > CYCLE_TIME) {
timer.stop();
}
move = (float)moveTime / (float)CYCLE_TIME;
if (move < 0.0001f) {
move = 0.0001f;
}
if (move > 0.9998f) {
move = 0.9998f;
}
repaint();
}
/* 测试用方法 */
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.add(new TextChangePane());
frame.setVisible(true);
}
/* 测试用方法 */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}