大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全家桶1年46,售后保障稳定
1.整体的结构图:
2.编写GameFrame03.java的代码:
package cn.bjsxt.test;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GameFrame03 extends Frame {
Image image = GameUtil.getImage(“images/sun.jpg”);
public void launchFrame() {
setSize(500, 500);
setLocation(100, 100);
setVisible(true);
new PaintThread().start();
addWindowListener(new WindowAdapter() {
// 单击右键选择“source”中的“override/implement
// methods”,frame里面勾选“windowClosed”点击“OK”
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private double x = 100, y = 100;
private double degree = 3.14 / 3;
private double speed = 13;
// 单击右键选择“source”中的“override/implement
// methods”,window里面勾选“paint(graphic)”点击“OK”
@Override
public void paint(Graphics g) {
g.drawImage(image, (int) x, (int) y, null);
if (speed > 0) {
speed -= 0.1;
} else {
speed = 0;
}
x += speed * Math.cos(degree);
y += speed * Math.sin(degree);
if (y > 500 – 130 || y < 30) {
degree = -degree;
}
if (x < 0 || x > 500 – 130) {
degree = Math.PI – degree;
}
}
class PaintThread extends Thread {
public void run() {
while (true) {
repaint();
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
GameFrame03 gf = new GameFrame03();
gf.launchFrame();
}
}
3.编写GameUtil.java的代码:
package cn.bjsxt.test;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class GameUtil {
private GameUtil() {
}
public static Image getImage(String path) {
URL u = GameUtil.class.getClassLoader().getResource(path);
BufferedImage image = null;
try {
image = ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
}
4.运行之后的结果:
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/226897.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...