JAVA入门级小程序,个人感觉可以引发外行人对JAVA产生一些兴趣,如果我刚接触JAVA的时候能碰到这种程序就好了,我就不会这么被动的学JAVA了,到现在也学的很零散,没能形成系统知识。兴趣是最好的老师。努力学习JAVA中。。。
以下贴出代码,附有程序运行结果图。所用代码均只用作演示,存在不少缺陷。
实现了键盘方向键控制的最简单的球的移动及边缘判定,打印出球的实时坐标。
/**
*
*/
package ballgame;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
/**
* 2014-6-11
*
* @author Gelar
*/
public class BallGame extends Frame {
/**
*
*/
private static final long serialVersionUID = 1L;
Image ball = Toolkit.getDefaultToolkit().getImage("images/ball.jpg");
double x = 250;
double y = 200;
double xCoord = 250;
double yCoord = 200;
boolean left, right, up, down;
public void paint(Graphics g) {
g.drawImage(ball, (int) x, (int) y, null);
if (left && x > 0) {
x = x - 10;
xCoord = x;
printCoords();
}
if (right && x < 470) {
x = x + 10;
xCoord = x;
printCoords();
}
if (up && y > 30) {
y = y - 10;
yCoord = y;
printCoords();
}
if (down && y < 370) {
y = y + 10;
yCoord = y;
printCoords();
}
}
void launchFrame() {
setSize(500, 400);
setLocation(420, 170);
setBackground(Color.black);
setTitle("Ball Game");
setVisible(true);
new PaintThread().start();
addKeyListener(new KeyMonitor());
printInitialCoords();
}
void printInitialCoords() {
System.out.println("(250.0,200.0)");
}
void printCoords() {
if (left || right || up || down) {
System.out.println("(" + xCoord + "," + yCoord + ")");
}
}
public static void main(String[] args) {
new BallGame().launchFrame();
}
class PaintThread extends Thread {
public void run() {
while (true) {
repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (37 == e.getKeyCode()) {
left = true;
}
if (39 == e.getKeyCode()) {
right = true;
}
if (38 == e.getKeyCode()) {
up = true;
}
if (40 == e.getKeyCode()) {
down = true;
}
}
public void keyReleased(KeyEvent e) {
if (37 == e.getKeyCode()) {
left = false;
}
if (39 == e.getKeyCode()) {
right = false;
}
if (38 == e.getKeyCode()) {
up = false;
}
if (40 == e.getKeyCode()) {
down = false;
}
}
}
}