参考自微信公众号:非著名程序员
package resources;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
// write your code here
try {
new DemoFrame();//实例化窗体
} catch (InterruptedException e) {
System.out.println("出现异常");
e.printStackTrace();
}
}
}
//控制图片动起来
//首先新建Demo类,用来存放图片对象
class Demo {
private int x, y, width, height;
private Image image;
public Demo() {
this.image = new ImageIcon("src//resources/demo.jpg").getImage();
this.width = 100;
this.height = 100;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Image getImage() {
return image;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
//不断刷新窗体
class DemoPlane extends JPanel {
private Demo demo;
public DemoPlane(Demo demo) {
this.demo = demo;
}
@Override
public void paint(Graphics g) {//在paint方法中我们实例化了一个ImageIcon对象,它的参数为图片
super.paint(g);//调用父类中被重写的方法,则必须使用关键字 super
g.drawImage(demo.getImage(),
demo.getX(), demo.getY(),
demo.getWidth(),demo.getHeight(), null); //而图像的观察者observer 参数,传递了null值,也可以传 this 即该类为图像的观察者。
// 当 observer 对象为非空时,原始图像更改时会通知观察者
}
}
//新建demoframe类并继承JFrame,完成图片的显示
class DemoFrame extends JFrame {
public DemoFrame() throws InterruptedException {
this.setTitle("Demo");//窗体标题
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗体退出
this.setSize(500, 500);//窗体默认宽度和高度
//this.setVisible(true);
// 设置显示窗体,默认为false
//实例DemoPlane
//Demo demo;//出问题了
Demo demo = new Demo();
DemoPlane plane = new DemoPlane(demo);
this.add(plane);//把plane添加到窗体中
this.setVisible(true);//把打开窗体显示移动到Demo类实例化以后,防止窗体显示前,demo对象没有被加载
while (true) {
Thread.sleep(1000);//画面每秒刷新一次
demo.setX(demo.getX() + 10);
demo.setY(demo.getY() + 10);
plane.repaint();//画面重新绘制
}
}
}