当我运行它时,重绘不起作用。框架打开并保持2000毫秒然后关闭。否则,如果我删除System.exit(0);声明,它没有关闭,但彩绘的球仍然没有出现。
BallWorld.java
import java.awt.*;
import javax.swing.JFrame;
public class BallWorld extends Frame {
public static void main(String[] args) {
BallWorld bw1 = new BallWorld(Color.red);
bw1.show();
}
public static final int framewidth = 600;
public static final int frameheight = 400;
private Ball aball;
private int counter = 0;
private BallWorld(Color ballColor){
setSize(framewidth,frameheight);
setTitle("Ball World");
aball = new Ball(10, 15, 5);
aball.setColor(ballColor);
aball.setMotion(3.0, 6.0);
}
public void paint(Graphics g){
aball.paint1(g);
aball.move();
if((aball.x() < 0) || (aball.x() > framewidth))
aball.setMotion(-aball.xMotion(), aball.yMotion());
if((aball.yMotion() < 0) || (aball.yMotion() > frameheight))
aball.setMotion(aball.xMotion(),-aball.yMotion());
//redraw the frame
counter = counter + 1;
if(counter < 2000)
repaint();
else
System.exit(0);
}
}
另一个班级是
Ball.java
import java.awt.*;
import java.awt.Rectangle;
public class Ball {
protected Rectangle location;
protected double dx,dy;
protected Color color;
public Ball(int x,int y, int r){
location =new Rectangle(x-r, y-r, 2*r, 2*r);
dx=0; //initially no motion
dy=0;
color = Color.blue;
}
// Setters
public void setColor(Color newColor){
color = newColor;
}
public void setMotion(double new_dx, double new_dy){
dx = new_dx;
dy = new_dy;
}
//Getters
public int radius(){
return location.width/2;
}
public int x(){
return location.x + radius();
}
public int y(){
return location.y + radius();
}
public double xMotion(){
return dx;
}
public double yMotion(){
return dy;
}
public Rectangle region(){
return location;
}
//Methods that change attributes of the ball
public void moveTo(int x, int y){
location.setLocation(x, y);
}
public void move(){
location.translate((int) dx,(int) dy);
}
public void paint1(Graphics g){
g.setColor(color);
g.fillOval(location.x, location.y,location.width,location.height);
}
}
答案 0 :(得分:3)
paint
,你实际上已经进入了不应该repaint
方法中调用repaint
或任何可能调用paint
的方法,它会创建一个消耗CPU的无限循环现在,问题的核心。基本上,你是在框架装饰下绘画。发生这种情况是因为窗口的可见区域内添加了装饰,而不是添加到其上。
有关详细信息,请参阅How to get the EXACT middle of a screen, even when re-sized和How can I set in the midst?
这就是为什么建议您不要覆盖顶级容器的颜料。您需要创建一个可以添加到框架中的组件,然后可以在其上绘制