一、创建项目
-
创建一个 demo0 项目。 -
在项目根目录中创建 image 文件夹,并把下面两张图片拷贝到 image 目录中。
-
图 1 -
图 2 -
在 src 中创建 BallGame 类。 -
目录结构如下:
二、出现窗口
-
代码:
import java.awt.*;
import javax.swing.*;
public class BallGame extends JFrame {
void launchFrame()
{
setSize(300,300);
setLocation(50,50);
setVisible(true);
}
public static void main(String[] args)
{
BallGame game = new BallGame();
game.launchFrame();
}
}
-
运行结果:
三、加载图片
-
代码:
import java.awt.*;
import javax.swing.*;
public class BallGame extends JFrame {
Image ball = Toolkit.getDefaultToolkit().getImage("image/ball.png");
Image desk = Toolkit.getDefaultToolkit().getImage("image/desk.jpg");
public void paint(Graphics g)
{
System.out.println("画了一次窗口");
g.drawImage(desk,0,0,null);
g.drawImage(ball,100,100,null);
}
void launchFrame()
{
setSize(856,500);
setLocation(50,50);
setVisible(true);
}
public static void main(String[] args)
{
BallGame game = new BallGame();
game.launchFrame();
}
}
-
运行结果: -
注意,有的时候窗口里的图片加载不出来,如下图: 遇到这种情况可以先将画出的窗口最小化,然后再从任务栏中把窗口打开,这样图片就加载出来了。
四、小球运动
-
代码:
import java.awt.*;
import javax.swing.*;
public class BallGame extends JFrame {
Image ball = Toolkit.getDefaultToolkit().getImage("image/ball.png");
Image desk = Toolkit.getDefaultToolkit().getImage("image/desk.jpg");
double x = 100;
double y = 250;
boolean right = true;
public void paint(Graphics g)
{
System.out.println(x);
g.drawImage(desk,0,0,null);
g.drawImage(ball,(int)x,(int)y,null);
if(right) x += 15; else x -= 15;
if(x > 780) right = false;
if(x < 36) right = true;
}
void launchFrame()
{
setSize(856,500);
setLocation(50,50);
setVisible(true);
while(true)
{
repaint();
try {
Thread.sleep(40);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
BallGame game = new BallGame();
game.launchFrame();
}
}
-
运行结果:
五、任意角度
-
代码:
import java.awt.*;
import javax.swing.*;
public class BallGame extends JFrame {
Image ball = Toolkit.getDefaultToolkit().getImage("image/ball.png");
Image desk = Toolkit.getDefaultToolkit().getImage("image/desk.jpg");
double x = 80;
double y = 250;
double maxX = 791;
double maxY = 430;
double minX = 35;
double minY = 65;
double degree = 3.14 / 3;
public void paint(Graphics g)
{
g.drawImage(desk,0,0,null);
g.drawImage(ball,(int)x,(int)y,null);
x += 10 * Math.cos(degree);
y += 10 * Math.sin(degree);
if(y > maxY || y < minY) degree = -degree;
if(x > maxX || x < minX) degree = 3.14 - degree;
}
void launchFrame()
{
setSize(856,500);
setLocation(50,50);
setVisible(true);
while(true)
{
repaint();
try {
Thread.sleep(40);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
BallGame game = new BallGame();
game.launchFrame();
}
}
-
运行结果:
|