Java | 移动的字符串(图形界面化的一个小练手)

实现要求:

在一个窗口中显示移动的字符串"Hello world",这段文字在窗口中从左到右来回移动。

提示:使用Timer或多线程,在一个面板上定时重绘该段字符串。

代码示例:

import java.awt.Font;
import java.awt.Graphics;

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

public class Test{
   public static void main(String[] args){
	   MoveFrame mf = new MoveFrame();
   }
}

class MoveFrame extends JFrame{
	public MoveFrame() {
		// TODO Auto-generated constructor stub
		setTitle("移动的字符串");
		setSize(400, 150);
		MovePanel mp = new MovePanel("Hello world");
		add(mp);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
}

class MovePanel extends JPanel implements Runnable{
	private Thread thread;
	private String string;
	private int x;
	private int step=1;
	public MovePanel(String s) {
		this.string=s;
		this.x=10;
		thread = new Thread(this);
		thread.start();
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		// TODO Auto-generated method stub
		super.paintComponent(g);
		g.setFont(new Font("Serif",Font.BOLD,24));
		g.drawString(this.string, x, 50);
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
			if(x+step<0 && step<0) {
				step = -step;
			}
			if(x+step>266 && step>0) {
				step = -step;
			}
			x+=step;
			repaint();
			
			try{
				thread.sleep(8);
			}
			catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
	
}

Guess you like

Origin blog.csdn.net/weixin_48419914/article/details/121477580