Advertisement
TermSpar

Images and Key Events

Aug 14th, 2016
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. import java.awt.event.KeyEvent;
  2. import java.awt.event.KeyListener;
  3.  
  4. import javax.swing.ImageIcon;
  5. import javax.swing.JFrame;
  6. import javax.swing.JLabel;
  7. import javax.swing.SwingUtilities;
  8.  
  9.  
  10. public class ImageTutorial {
  11.  
  12.     //Frame Vars:
  13.     private JFrame frame = new JFrame();
  14.     private JLabel player = new JLabel();
  15.    
  16.     //Movement Vars:
  17.     private int moveSpeed = 15;
  18.    
  19.     public ImageTutorial() {
  20.         //Frame Attributes:
  21.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  22.         frame.setLayout(null);
  23.         frame.setVisible(true);
  24.         frame.setResizable(false);
  25.         frame.setSize(600, 600);
  26.         frame.setTitle("Image Tutorial");
  27.        
  28.         //Player Attributes:
  29.         player.setBounds(150, 150, 250, 150);
  30.         player.setIcon(new ImageIcon("D:\\Documents\\Visual Studio 2015\\Projects\\CarCrashSim\\CarCrashSim\\redCar.png"));
  31.        
  32.         frame.add(player);
  33.         SwingUtilities.updateComponentTreeUI(frame);
  34.        
  35.         //Key Events:
  36.         frame.addKeyListener(new KeyListener(){
  37.  
  38.             public void keyPressed(KeyEvent e) {
  39.                 if(e.getKeyCode() == KeyEvent.VK_RIGHT){
  40.                     player.setLocation(player.getLocation().x + moveSpeed, player.getLocation().y);
  41.                 }
  42.                 else if(e.getKeyCode() == KeyEvent.VK_LEFT){
  43.                     player.setLocation(player.getLocation().x - moveSpeed, player.getLocation().y);
  44.                 }
  45.                 else if(e.getKeyCode() == KeyEvent.VK_UP){
  46.                     player.setLocation(player.getLocation().x, player.getLocation().y - moveSpeed);
  47.                 }
  48.                 else if(e.getKeyCode() == KeyEvent.VK_DOWN){
  49.                     player.setLocation(player.getLocation().x, player.getLocation().y + moveSpeed);
  50.                 }
  51.             }
  52.  
  53.             public void keyReleased(KeyEvent e) {
  54.                
  55.             }
  56.  
  57.             public void keyTyped(KeyEvent e) {
  58.                
  59.             }
  60.            
  61.         });
  62.        
  63.     }
  64.    
  65.     public static void main(String[] args){
  66.         new ImageTutorial();
  67.     }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement