java swing里面的repaint()方法怎么用
来源:百度知道 编辑:UC知道 时间:2024/09/28 08:02:25
请看代码
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);
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);
你可以再定义两个成员变量
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();
}
非常简单 将
x=x++;
y=y++;改成
x++;
y++;就行了