效果:一个可以移动的变色圆圈
源代码:
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame{
int x=70;
int y=70;
public static void main(String[]args){
Test gui=new Test();
gui.go();
}
public void go(){
JFrame frame=new JFrame();
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//定义绘画区域
MyDrawPanel drawPanel=new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
for (int i=0;i<130;i++){
x++;y++;
drawPanel.repaint();
try{
Thread.sleep(50);
}catch (Exception ex){}
}
}
class MyDrawPanel extends JPanel{
@Override
public void paintComponent(Graphics g){
//将颜色设置为白色,并且将旧的圆圈变成白色,以实现目的
g.setColor(Color.white);
g.fillRect(0,0,this.getWidth(),this.getHeight());
//小伙伴如果没有看懂上面两行代码的作用,可以将其注释掉,在运行一次
Graphics2D g2d=(Graphics2D) g;
int red=(int)(Math.random()*255);
int green=(int)(Math.random()*255);
int blue=(int)(Math.random()*255);
Color startColor=new Color(red,green,blue);
g.setColor(startColor);
g.fillOval(x,y,40,40);
}
}
}