public class loc
{
public int x;
public int y;
public int radius;
public loc(int x,int y,int r)
{
this.x=x;
this.y=y;
this.radius=r;
}
public int getX() {
return this.x;
}
public void setX(int x) {
this.x =x;
}
public int getY() {
return this.y;
}
public void setY(int y) {
this.y =y;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;
public class Display extends JPanel
{
public loc [] ar=new loc[5];
private int dx=1;
private int dy=1;
public Display()
{
for(int i=0; i<5; i++)
this.ar[i]=new loc(new Random().nextInt(615)+25,new Random().nextInt(615)+25,new Random().nextInt(30)+25);
}
public void paintComponent(Graphics g)
{
g.setColor(Color.darkGray); // clear the frame ...
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.red);
for(int i=0; i<ar.length; i++)
g.fillOval(ar[i].x, ar[i].y, ar[i].radius,ar[i].radius);
update();
}
public void update()
{
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
check();
repaint();
}
public void check()
{
for(int i=0; i<ar.length; i++)
{
if(ar[i].x<0)
dx=1;
if(ar[i].x>=this.getWidth()-45)
dx=-1;
if(ar[i].y<0)
dy=1;
if(ar[i].y>=this.getHeight()-45)
dy=-1;
ar[i].x+=dx;
ar[i].y+=dy;
}
}
}
主要课程:
import javax.swing.JFrame;
public class MAIN1 {
public static void main(String[] args)
{
Display b=new Display();
JFrame j=new JFrame();
j.setSize(700, 700);
j.add(b);
j.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
j.setVisible(true);
}
loc类包括: 随机(x),随机(Y)球和随机(半径)。 Display类是绘制球的类。
代码是绘制圆圈并移动它们,但圆圈移动不好。 我的问题是圈子不是由他们自己移动;但我希望圈子会自己移动。
我该怎么办?