import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class myJPanel extends JPanel implements ActionListener, KeyListener { private Timer shotTimer; private int delay=100; private int shipX=0; private int shipY=530; private int shotX=-20; private int shotY=530; private Color myColor = Color.BLUE; JButton b; public myJPanel() { super(); //create the timer. shotTimer = new Timer(delay, this); shotTimer.addActionListener(this); setLayout(new BorderLayout()); b = new JButton(""); b.addKeyListener(this); b.requestFocusInWindow(); //create the new panel, and add the buttons JPanel colorPanel = new JPanel(); //keys colorPanel.add(b); //add to the panel add(colorPanel, BorderLayout.SOUTH); } /***************** * Paint *****************/ public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.fillOval(shotX, shotY, 10, 10); g.setColor(myColor); g.fillRect(shipX,shipY,15, 5); } /*********************** * Regular Actions ***********************/ public void actionPerformed(ActionEvent event) { Object obj = event.getSource(); if(obj == shotTimer) { //check if the ball has reached the top. if so break the timer if(shotY>=550) { shotX = 0; shotY = 530; repaint(); shotTimer.stop(); } shotY-=10; repaint(); } } public void keyPressed(KeyEvent e) { int x = e.getKeyCode(); //left arrow if(x == e.VK_LEFT) { if (shipX>=10) shipX-=10; repaint(); } //Right arrow if(x == e.VK_RIGHT) { if (shipX<=460) shipX+=10; repaint(); } //Space if(x == e.VK_SPACE) { shotX = shipX; shotTimer.start(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } }