Problem:
Create a java application that changes an arrow based on the user's input.
You're responsible for adding the pictures of the arrow.

You're responsible for adding the pictures of the arrow.
Output:
Solution:
//****************ArrowControlFrame.java********************/ import javax.swing.JFrame; public class ArrowControlFrame { public static void main(String[] args) { JFrame frame = new JFrame(""); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new ArrowControlPanel()); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } } //****************ArrowControlPanel.java****************/ import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.ImageIcon; import javax.swing.JPanel; public class ArrowControlPanel extends JPanel { private ImageIcon up, down, left, right, current; private int x, y; private final int JUMP = 10; private final int WIDTH = 400, HEIGHT = 300; public ArrowControlPanel() { up = new ImageIcon(getClass().getResource("arrowUp.gif")); down = new ImageIcon(getClass().getResource("arrowDown.gif")); left = new ImageIcon(getClass().getResource("arrowLeft.gif")); right = new ImageIcon(getClass().getResource("arrowRight.gif")); current = up; x = WIDTH / 2; y = HEIGHT / 2; addKeyListener(new KeyEventHandler()); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setBackground(Color.BLACK); setFocusable(true); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); current.paintIcon(this, g, x, y); } private class KeyEventHandler implements KeyListener { @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_UP: current = up; y -= JUMP; break; case KeyEvent.VK_DOWN: current = down; y += JUMP; break; case KeyEvent.VK_RIGHT: current = right; x+= JUMP; break; case KeyEvent.VK_LEFT: current = left; x-= JUMP; break; } repaint(); } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } }
No comments :
Post a Comment