我是初学者java课程。我们处于图形的早期阶段。我的任务是创建一个使用图片拍子弹的程序。我有一个宇宙飞船图像图标和我的听众。
My Bullet课程如下
package Shooting;
int x, y, height;
int xShoot, yShoot;
Color bullet = new Color(0,255,0);
public Bullet(int x, int y)
{
this.x = x;
this.y = y;
}
public void setY(int y)
{
this.y = y;
}
public int getY()
{
return y;
}
public void setX(int x)
{
this.x = x;
}
public int getX()
{
return x;
}
public void draw(Graphics page)
{
page.setColor(bullet);
page.fillOval(xShoot, yShoot, 10, 10);
}
public void redraw(Graphics page)
{
page.setColor(bullet);
page.fillOval(xShoot, yShoot - 5, 10, 10);
}
public void setXShoot(int xShoot)
{
this.xShoot = xShoot;
}
public void setYShoot(int yShoot)
{
this.yShoot = yShoot;
}
public void remove(Graphics page)
{
x = -40;
y = 10;
page.setColor(Color.GRAY);
}
}
我的小组如下
package Shooting;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Shooter extends JPanel
{
int shipX = 50;
int bulletX = shipX + 25;
int shipY = 600;
int y = 595;
int bulletY = 700 - 5;
JPanel panel = new JPanel();
final int MOVE = 10;
Bullet bullet = new Bullet(bulletX, bulletY);
ArrayList<Bullet> bullets = new ArrayList<>();
ImageIcon ship = new ImageIcon("klingon.png");;
final int DELAY = 2;
private Timer timer;
///Graphics page;
public void paintComponent(Graphics page)
{
super.paintComponent(page);
///this.page = page;
ship.paintIcon(this, page, shipX, shipY);
}
public Shooter()
{
addKeyListener(new ShipListener());
addKeyListener(new BulletListener());
timer = new Timer(DELAY, new FiringListener());
setBackground(Color.BLACK);
timer.start();
}
private class ShipListener implements KeyListener
{
public void keyPressed(KeyEvent event)
{
switch(event.getKeyCode())
{
case KeyEvent.VK_LEFT:
shipX = shipX - MOVE;
repaint();
break;
case KeyEvent.VK_RIGHT:
shipX = shipX + MOVE;
repaint();
break;
}
repaint();
}
public void keyTyped(KeyEvent event){}
public void keyReleased(KeyEvent event){}
}
private class BulletListener implements KeyListener
{
public void keyPressed(KeyEvent event)
{
switch(event.getKeyCode())
{
case KeyEvent.VK_SPACE:
bullet.setX(shipX + 25);
bullet.setY(shipY);
bullet.draw(getGraphics());
repaint();
}
repaint();
}
public void keyTyped(KeyEvent event){}
public void keyReleased(KeyEvent event){}
}
private class FiringListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
bullet.setY(y - 5);
repaint();
}
}
}
我的司机
package Shooting;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class ShooterDriver
{
public static void main(String []args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Shooter shooter = new Shooter();
frame.getContentPane().add(shooter);
frame.pack();
frame.setVisible(true);
}
}
感谢任何帮助。我只需要我的听众工作。左右键可以移动船只和太空进行射击。 谢谢。