1 addkeylistenerthis 2 int code egetkeycode 3

This preview shows page 13 - 18 out of 23 pages.

1. addKeyListener(this); 2. int code = e.getKeyCode(); 3. moveAmount = SIZE; 4. requestFocusInWindow(); 5. g.fillOval(ball.x, ball.y, ball.width, ball.height); 6. repaint(); 7. ball = new Rectangle(LINE_START_X-SIZE/2, LINE_Y - SIZE/2, SIZE, SIZE); 8. addMouseListener(this); 9. ball.x = ball.x + moveAmount; 10. moveAmount = -SIZE; 11. if (code == KeyEvent.VK_UP) { t.start(); } else if (code == KeyEvent.VK_DOWN) { t.stop(); } 12. t = new Timer(200, this); 13. g.drawLine (LINE_START_X, LINE_Y, LINE_END_X, LINE_Y);
Image of page 13

Subscribe to view the full document.

- 14 - COMPSCI 101 Question/Answer Sheet ID: ..................................................................... CONTINUED import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AJPanel extends JPanel implements ActionListener, MouseListener, KeyListener { private static final int SIZE = 40; private static final int LINE_Y = 70; private static final int LINE_START_X = 50; private static final int LINE_END_X = LINE_START_X + 10*SIZE; private Timer t; private Rectangle ball; private int moveAmount; public AJPanel() { moveAmount = SIZE; } public void keyPressed(KeyEvent e) { } public void actionPerformed(ActionEvent e) { if(ball.x+SIZE >= LINE_END_X) { } else if(ball.x <= LINE_START_X) { } } public void paintComponent(Graphics g) { super.paintComponent(g); } public void mousePressed(MouseEvent e) { }
Image of page 14
- 15 - COMPSCI 101 Question/Answer Sheet ID: ..................................................................... CONTINUED public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} } (13 marks)
Image of page 15

Subscribe to view the full document.