java 实现显示屏上字符串滚动显示的效果

今天路过一家商店看到滚动的显示屏,就做了这个很简单又好玩的程序,用java实现字符串滚动显示。O(∩_∩)O

下面是源代码:

package main.slidetext;
package main.slidetext;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SlideText extends JFrame{
	private static final long serialVersionUID = 4171454850759140121L;
	private JPanel text;
	private static String str = "Welcome! This is for 'SlideText' test! ";		// 显示文本
	private int x = 10;
	
	public SlideText() {
		setTitle("Slide Text");
		Dimension src = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((src.width - getWidth()) / 2, (src.height - getHeight()) / 2);
		text = new JPanel(){
			private static final long serialVersionUID = 7633828902009421639L;
			@Override
			public void paint(Graphics g) {
				g.setColor(Color.LIGHT_GRAY);
				g.fillRect(0, 0, getWidth(), getHeight());
				g.setColor(Color.CYAN);
				Font font = new Font("Consolas", Font.PLAIN, 30);
				g.setFont(font);
				FontMetrics fm = g.getFontMetrics();
				int strWidth = fm.stringWidth(str);							// 得到字符串的宽度
				int width = text.getWidth();								// 得到显示屏的宽度
				if(x < 0 && Math.abs(x) > width){
					x = 10;
				}
				g.drawString(str, x, 35);
				g.drawString(str, strWidth + 10 + x, 35);
			}
			@Override
			public void update(Graphics g) {
				paint(g);
			}
			
		};
		text.setPreferredSize(new Dimension(660, 45));
		add(text);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while(true){
						// 改变显示的位置 
						x = x - 4;
						repaint();
						Thread.sleep(50);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		enableInputMethods(false);
		pack();
		setResizable(false);
		setVisible(true);
	}

}

 
  


效果如下:

java 实现显示屏上字符串滚动显示的效果_第1张图片


你可能感兴趣的:(java)