我当中的打印语句为什么打出来都是x=10?怎么才能让x,y递加呢?

请看代码
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 opaque
frame.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()函数可以放置变量初始化语句,可以在桌面程序里面怎么搞呢?

跃然一笑
浏览 192回答 2
2回答

湖上湖

你可以再定义两个成员变量int oldX;用来保存上一次paint时的xint oldY;用来保存上一次paint时的ypublic 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();} 

慕村9548890

非常简单 将x=x++;y=y++;改成x++;y++;就行了
打开App,查看更多内容
随时随地看视频慕课网APP