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

导读:本篇文章讲解 Java | 移动的字符串(图形界面化的一个小练手),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

实现要求:

在一个窗口中显示移动的字符串”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();
			}
		}
	}
	
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/103062.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!