Java GUI 绘制中的重绘repaint()
作者:互联网
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Test_repaint extends JFrame {
//无参构造
public Test_repaint(){
setTitle("绘制-重绘");
setSize(800, 100);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//添加绘制对象
add(new MovingMessagePanel());
setVisible(true);
}
public static void main(String[] args){
new Test_repaint();
}
/**
* 绘制类
* extends JPanel:继承模版类
*/
static class MovingMessagePanel extends JPanel{
//绘制内容
private String message = "I LOVE GUI";
//绘制内容x,y坐标
private int x = 0;
private int y = 50;
//绘制类的无参构造
public MovingMessagePanel(){
// 创建计时器,100ms是周期
Timer timer = new Timer(100, new TimerListener());
timer.start();// 启动定时器
}
// 重写模版类的绘制方法
@Override
protected void paintComponent(Graphics g){
//跟新,删除跟新当前绘制
super.paintComponent(g);
//当绘制的内容到达最右侧时给x坐标重新赋值到初始时
if (x > getWidth()){
x = 0;
}
x += 5;
// 应该先进行字体的设定,再对字体进行显示和移动,否则会按照默认的字体格式类显示字体
g.setFont(new Font("TimesRoman", Font.PLAIN, 50));
//设置绘制内容颜色
g.setColor(new Color(100, 100, 200));
// 怎么改变字体的大小和颜色?
g.drawString(message, x, y);
}
/**
* 监听类
* implements ActionListener:实现监听
*/
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
/**
* 每次重新绘制时paintComponent会重新绘制一遍,
* 而每一次调用都会改变xCoordinate,
* 这就实现了字符的移动
*/
repaint();
}
}
}
}
执行结果:
标签:repaint,Java,java,GUI,import,new,绘制,public 来源: https://www.cnblogs.com/clf125800/p/16424978.html