请看代码import java.awt.Graphics;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.JPanel;public class Test extends JPanel{int x,y;public Test(int x,int y){this.x = x;this.y = y;}public void paint(Graphics g){g.fillOval(x-1,y-1,3,3);x=x++;y=y++;System.out.println("x="+x);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}repaint();}public static void main(String [] args){run();}public static void run(){JFrame frame = new JFrame("TEST Animation");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Create and set up the content pane.JComponent newContentPane = new Test(10,10);newContentPane.setOpaque(true); //content panes must be opaqueframe.setContentPane(newContentPane);//Display the window.frame.setSize(800,600);frame.setResizable(false);frame.setVisible(true);}}我当中的打印语句为什么打出来都是x=10啊怎么才能让x,y递加呢补充下运行此程序可以在控制台中看到每隔1000毫秒打印x=10,说明系统正确调用的repaint(),但是每次好像又重新初始化x,y,我知道在applet中有start()函数可以放置变量初始化语句,可以在桌面程序里面怎么搞呢?
2 回答
湖上湖
TA贡献2003条经验 获得超2个赞
你可以再定义两个成员变量
int oldX;用来保存上一次paint时的x
int oldY;用来保存上一次paint时的y
public void paint(Graphics g){
//擦去原来的点
Color c = g.getColor();
g.setColor(this.getBackGround());
g.fillOval(oldX-1,oldY-1,3,3);
g.setColor(c);
//保存点
oldX = x;
oldY = y;
g.fillOval(x-1,y-1,3,3);
x++;
y++;
System.out.println("x="+x);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
添加回答
举报
0/150
提交
取消
