Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package javaapplication1;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.Image;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- public class JavaGame extends JFrame implements Runnable{
- int x, y, xDirection, yDirection;
- private Image dbImage;
- private Graphics dbg;
- Image face;
- Font font = new Font("Arial", Font.BOLD | Font.CENTER_BASELINE, 30);
- public void run(){
- try{
- while(true){
- move();
- Thread.sleep(10);
- }
- }
- catch(Exception e){
- System.out.println("ERROR");
- }
- }
- public void move(){
- x += xDirection;
- y += yDirection;
- if(x <= 10)
- x = 10;
- if(x >= 200)
- x = 200;
- if(y <= 25)
- y = 25;
- if(y >= 250)
- y = 250;
- }
- public void setXDirection(int xdir){
- xDirection = xdir;
- }
- public void setYDirection(int ydir){
- yDirection = ydir;
- }
- public class AL extends KeyAdapter {
- private int keyCode;
- public void keyPressed(KeyEvent e){
- int keyCode = e.getKeyCode();
- if(keyCode == e.VK_LEFT){
- setXDirection(-1);
- }
- if(keyCode == e.VK_RIGHT){
- setXDirection(+1);
- }
- if(keyCode == e.VK_UP){
- setYDirection(-1);
- }
- if(keyCode == e.VK_DOWN){
- setYDirection(+1);
- }
- }
- public void keyReleased(KeyEvent e){
- if(keyCode == e.VK_LEFT){
- setXDirection(0);
- }
- if(keyCode == e.VK_RIGHT){
- setXDirection(0);
- }
- if(keyCode == e.VK_UP){
- setYDirection(0);
- }
- if(keyCode == e.VK_DOWN){
- setYDirection(0);
- }
- }
- }
- public JavaGame(){
- //Load Image
- ImageIcon i = new ImageIcon("C:/Documents and Settings/Administrator/My Documents/NetBeansProjects/javagame/src/javaapplication1/this.gif");
- face = i.getImage();
- //Game Properties
- addKeyListener(new AL());
- setTitle("JavaGame");
- setSize(250, 250);
- setResizable(false);
- setLocationRelativeTo(null);
- setVisible(true);
- getContentPane().setBackground(Color.cyan);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- x = 150;
- y = 150;
- }
- public void paint(Graphics g){
- dbImage = createImage(getWidth(),getHeight());
- dbg = dbImage.getGraphics();
- paintComponent(dbg);
- g.drawImage(dbImage, 0, 0, this);
- }
- public void paintComponent(Graphics g){
- super.paint(g);
- g.setFont(font);
- g.setColor(Color.BLUE);
- g.drawString("Is this a game?", 50, 50);
- g.setColor(Color.GREEN);
- g.drawImage(face, x, y, this);
- repaint();
- }
- public static void main(String[] args) {
- JavaGame jg = new JavaGame();
- //Threads
- Thread t1 = new Thread(jg);
- t1.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement