我想在JFrame中或者Frame中添加一张背景图片,然后在这图片上画出会移动的小球,怎么实现?我的代码把添加背景图片去掉,小球就正常运行了,
怎么修改啊?
希望各位大侠指教
不胜感激!!!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestItem extends JFrame {
JLabel jl;
Bullet b = new Bullet(80,80);
public static void main(String[] args) {
new TestItem().lauchFrame();
}
public void lauchFrame() {
jl = new JLabel();
ImageIcon image = new ImageIcon("Images\\mainBack.png");
jl.setIcon(image);
jl.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
this.setTitle("坦克大战");
this.setSize(246, 350);
this.setVisible(true);
this.getLayeredPane().add(jl, new Integer(Integer.MIN_VALUE));
((JPanel)getContentPane()).setOpaque(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setBackground(Color.black);
new Thread(new paintThread()).start();
this.addKeyListener(new keyMonitor());
}
public void paint(Graphics g) {
b.draw(g);
}
private class paintThread implements Runnable {
public void run() {
while(true) {
repaint();
try {
Thread.sleep(80);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class keyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
b.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
b.keyReleased(e);
}
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
public class Bullet {
private int x;
private int y;
private static final int width = 16;
private static final int height = 16;
private static final int speed = 8;
Direction dir = Direction.D;
private boolean bU = false,bR = false,bD = false,bL = false;
public Bullet(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void draw(Graphics g) {
Color c = g.getColor();
g.setColor(Color.yellow);
g.fillOval(x, y, width, height);
g.setColor(c);
move();
}
private void move() {
switch(dir) {
case U:
y -= speed;
break;
case R:
x += speed;
break;
case D:
y += speed;
break;
case L:
x -= speed;
break;
}
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
bU = true;
break;
case KeyEvent.VK_RIGHT:
bR = true;
break;
case KeyEvent.VK_DOWN:
bD = true;
break;
case KeyEvent.VK_LEFT:
bL = true;
break;
}
licalDirection();
}
private void licalDirection() {
if(bU && !bR && !bD && !bL) {
dir = Direction.U;
} else if(!bU && bR && !bD && !bL) {
dir = Direction.R;
} else if(!bU && !bR && bD && !bL) {
dir = Direction.D;
} else if(!bU && !bR && !bD && bL) {
dir = Direction.L;
}
}
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
bU = false;
break;
case KeyEvent.VK_RIGHT:
bR = false;
break;
case KeyEvent.VK_DOWN:
bD = false;
break;
case KeyEvent.VK_LEFT:
bL = false;
break;
}
licalDirection();
}
}
public enum Direction {
U,R,D,L;
}