how can i set an object in focus

Ads
 

how can i set an object in focus

There is a Canvas object in my game and this object is not set in focus, because of this my snake is not moving on the Board .

Basically i am working on snake game project, and i want is when play button is clicked from PlayGame.java JDialog ,game should start ,but problem i am facing is after clicking button gamescreen appearing on window but snake is not moving, so someone suggest me that your canvas object is not in focus whenever it is called. that is why KeyLisener not able to listen to keyPresses /key strokes.

This is the class in which canvas object is declared and implemented.

package org.psnbtech;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import org.psnbtech.GameBoard.TileType;
import org.psnbtech.Snake.Direction;


public class Engine extends KeyAdapter {

    private static final int UPDATES_PER_SECOND = 15;

    private static final Font FONT_SMALL = new Font("Arial", Font.BOLD, 20);

    private static final Font FONT_LARGE = new Font("Arial", Font.BOLD, 40);

    public Canvas canvas;

    public GameBoard board;

    public Snake snake;

    public int score;

    public boolean gameOver;


    public Engine(Canvas canvas) {
                this.canvas = canvas;
            this.board = new GameBoard();
        this.snake = new Snake(board);

        resetGame();

        canvas.addKeyListener(this);
                //new Engine(canvas).startGame();
    }


    public void startGame() {
        canvas.createBufferStrategy(2);

        Graphics2D g = (Graphics2D)canvas.getBufferStrategy().getDrawGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        long start = 0L;
        long sleepDuration = 0L;
        while(true) {
            start = System.currentTimeMillis();

            update();
            render(g);

            canvas.getBufferStrategy().show();

            g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());

            sleepDuration = (1500L / UPDATES_PER_SECOND) - (System.currentTimeMillis() - start);

            if(sleepDuration > 0) {
                try {
                    Thread.sleep(sleepDuration);
                } catch(Exception e) {
                                    e.printStackTrace();
                }
            }
        }
    }

    public void update() {
        if(gameOver || !canvas.isFocusable()) {
            return;
        }
        TileType snakeTile = snake.updateSnake();
        if(snakeTile == null || snakeTile.equals(TileType.SNAKE)) {
            gameOver = true;
        } else if(snakeTile.equals(TileType.FRUIT)) {
            score += 10;
            spawnFruit();
        }
    }

    public void render(Graphics2D g) {
        board.draw(g);

        g.setColor(Color.WHITE);

        if(gameOver) {
            g.setFont(FONT_LARGE);
            String message = new String("Your Score: " + score);
            g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 250);

            g.setFont(FONT_SMALL);
            message = new String("Press Enter to Restart the Game");
            g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 350);
        } else {
            g.setFont(FONT_SMALL);
            g.drawString("Score:" + score, 10, 20);
        }
    }

    public void resetGame() {
        board.resetBoard();
        snake.resetSnake();
        score = 0;
        gameOver = false;
        spawnFruit();
    }

    public void spawnFruit() {
        int random = (int)(Math.random() * ((GameBoard.MAP_SIZE * GameBoard.MAP_SIZE) - snake.getSnakeLength())); // if '*' replace by '/' then only one fruit is there for snake

        int emptyFound = 0;
        int index = 0;
        while(emptyFound < random) {
            index++;
            if(board.getTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE).equals(TileType.EMPTY)) { // if '/' replaced by '*' then nothing displays on the board 
                emptyFound++;
            }
        }
        board.setTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE, TileType.FRUIT); // it also show nothing when replacing '/' by '/' 
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if((e.getKeyCode() == KeyEvent.VK_UP)||(e.getKeyCode() == KeyEvent.VK_W)) {
            snake.setDirection(Direction.UP);
        }
        if((e.getKeyCode() == KeyEvent.VK_DOWN)||(e.getKeyCode() == KeyEvent.VK_S)) {
            snake.setDirection(Direction.DOWN);
        }
        if((e.getKeyCode() == KeyEvent.VK_LEFT)||(e.getKeyCode() == KeyEvent.VK_A)) {
            snake.setDirection(Direction.LEFT);
        }
        if((e.getKeyCode() == KeyEvent.VK_RIGHT)||(e.getKeyCode() == KeyEvent.VK_D)) {
            snake.setDirection(Direction.RIGHT);
        }
        if(e.getKeyCode() == KeyEvent.VK_ENTER && gameOver) {
            resetGame();
        }
    }

         public static void main(String[] args)  {
        new PlayGame().setVisible(true);

        /**JFrame frame = new JFrame("SnakeGame");
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setResizable(false);

        Canvas canvas = new Canvas();
        canvas.setBackground(Color.black);
        canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));

        frame.getContentPane().add(canvas);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true); 

        new Engine(canvas).startGame();*/


             }        
}

And also i am attching actionPerformed() method of Play Button where i am referring canvas object

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

JFrame frame = new JFrame("SnakeGame"); 
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setResizable(false);

Canvas canvas = new Canvas();
canvas.setBackground(Color.black);
canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE

*GameBoard.TILESIZE,GameBoard.MAPSIZE * GameBoard.TILE_SIZE));

frame.add(canvas);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true); 

new Engine(canvas).startGame();

}

So please tell/suggest me how can i set canvas object in focus

View Answers

Ads









Related Tutorials/Questions & Answers:
how can i set an object in focus
how can i set an object in focus  There is a Canvas object in my game and this object is not set in focus, because of this my snake is not moving... is not moving, so someone suggest me that your canvas object is not in focus
How to make focus on an object, make focus on an object, focus on an object
How to make focus on an object       This example will teach you to make focus on the object so follow...: Choose Polygonal lasso tool (L key) to make selection of the object. Blur
Advertisements
please tell anybody how can i set a value in hiperlink for edit n delete link
please tell anybody how can i set a value in hiperlink for edit n delete link  <logic:present name="allRecords"> <logic:notEmpty name="allRecords"> <logic:iterate id="user" name
How can I do it? .click();
How can I do it? .click();  I have a very unusual problem. I want...("a"); x.click(); </script> So it's click on an element witch one Id's is "a", but I want that it make mouseup in this element. How can I do it, because if I write
How can I learn Java?
How can I learn Java?  Hi, I have just completed a course in HTML and C programming language. I have some programming experience in visual basic... programming. How can I learn Java? in shortest possible time. I mean I just want to begin
how should i can solve
how should i can solve  Web based program - Input - Person's contact details with Passport Number as Unique Key. Save data in to oracle / MySQL. Output - List of Persons saved in the database. Technology to be used - JSP
how to set values in object using java and what are the ways?
how to set values in object using java and what are the ways?  How to set values in object using java ?what are the ways
How I can cast a variable in Scala?
How I can cast a variable in Scala?  Hi, Trying Big Data and now I... an object of Graphics and you wan to cast it to Graphics2D then you can use following code: g.asInstanceOf[Graphics2D]; Similarly you can apply this logic to all
How I can cast a variable in Scala?
How I can cast a variable in Scala?  Hi, Trying Big Data and now I... an object of Graphics and you wan to cast it to Graphics2D then you can use following code: g.asInstanceOf[Graphics2D]; Similarly you can apply this logic to all
How can I show users privileges in MySQL?
How can I show users privileges in MySQL?  Hi, How can I show user's privileges in MySQL? I want to know what is accessible to user in MySQL database. How to check this? Thanks   Hi, To view grant for a user you can
How can I change UIButton title color?
How can I change UIButton title color?  Hi, I have a button in my iPhone/iPad application. I want to change the color of the text when user clicks..., You have to set the color of the button for a particular state say
how can i add hibernate plugin to eclipse?
how can i add hibernate plugin to eclipse?  how can i add hibernate plugin to eclipse
how i can get jqfade.js library
how i can get jqfade.js library  how i can get jqfade.j script library
how can i display a pdf file in a jtextarea
how can i display a pdf file in a jtextarea  I need to display a pdf file in a jtextfield or in a jtextarea.Atlest i need to displat it in a jframe.I have a button and while clicking on it ,i need to choose the pdf file and need
how can i remove newline characters and tabs
how can i remove newline characters and tabs   how can i remove newline characters and tabs ? but i wont to using GUI .please help
how can i make monthly register ?
how can i make monthly register ?  how can i make monthly register ? iam using jdeveloper
how can i display a editable result of form?
how can i display a editable result of form?  how can i display a editable result of form? i know how to display form result but the result... show the result but i can not modify the result. how can i display modifyable
how can i create a discussion forum?
how can i create a discussion forum?  how can i create a discussion forum for my e- mentoring site for women which can be used by a registered user only. i am using jsp and servlets and i am working with netbeans 6.8.
How can i modify my account in roseindia
How can i modify my account in roseindia  Presently am not using my gmail id. I have to modify my roseindia account. Please send the answer to following mail id
How do I set environment variables from Java?
How do I set environment variables from Java?  How do I set environment variables from Java
How can I master Java in one month?
How can I master Java in one month?  Hi, I wish to learn Java programming in one month. I have little experience in c programming and PHP programming. Is there any way to learn Java quickly. How can I master Java in one month
how can i print the selected content of a frame
how can i print the selected content of a frame  hello sir, I am designing a bill calculate program. I want to print the bill in crystal form. I want to skip all the text fields shapes and all the button from the frame.. but all
How can i use Facebook connect button
How can i use Facebook connect button  Please to meet you all guys I wonder how can i use this Connect to facebook for me to post in a particular... http://likekhevy4.blogspot.com/ How can i apply this kind of comment with "Connect
How can I create sessionfactory in Hibernate?
How can I create sessionfactory in Hibernate?  HELLO, How can I create sessionfactory in Hibernate? If you can explain me with example that would... with the links below: Hibernate 4 Hibernate Session Factory I hope
How can i search and insert within a query
How can i search and insert within a query  if it is possible... semester and degree if i search batch 2008 , semester first and degree bscs then search..., terminal) in another table. i am trying these but not successful, A problem occur
how can i hide and show tables
how can i hide and show tables  hai, i am creating a form which the code is included below i want to hide the tables initially and after i click go i want to display the tables with result.so any help is appreciated much <
Object reference not set to an instance of an object
Object reference not set to an instance of an object  Object reference not set to an instance of an object
How many cookie object we can store in a session? is there any limit?
How many cookie object we can store in a session? is there any limit?  How many cookie object we can store in a session? is there any limit
JavaScript focus method
;  JavaScript focus method can be used to set focus..._Object.focus(); Where element_Object is the element to whom we have to set focus... are providing you a simple example to set the focus to the input text box. Not only
How can I access databse through JSP. I am using postgresql-8.4.4-1-windows as database and jboss-4.0.5.GA as server.
How can I access databse through JSP. I am using postgresql-8.4.4-1-windows as database and jboss-4.0.5.GA as server.  I am using postgresql-8.4.4-1... netbeans-6.1-ml-windows.How can I set up connection to database? Please help me
how can i use ajax and jquery in netbeans ide
how can i use ajax and jquery in netbeans ide  i am using .net here we hav to download ajax controls and if i use netbeans ide and uses ajax control so from where i can get these controls.also i want to know which struct book i

Ads