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 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









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... of the object. ADS_TO_REPLACE_2 Blur effect: Go to Filter menu > Blur >Apply
Advertisements
How I can Set Transparent Background Image to Panel - Java Beginners
How I can Set Transparent Background Image to Panel  Sir ,How I can Set Transperent Background Image to Jpanel. plz Help Me
How can I initialize the JSONArray and JSON object with data?
How can I initialize the JSONArray and JSON object with data?  How can I initialize the JSONArray and JSONObject with data
set the focus on an element using Javascript
set the focus on an element using Javascript  How to set the focus on an element using Javascript
Null value when i set interface object in form controller - Spring
Null value when i set interface object in form controller   Hi all, i am very new about spring and hibernate. i got null value when i set... to manipulate data with new table , i can do CRUD operation operation with new table
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 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
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 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 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
JavaScript focus method
;  JavaScript focus method can be used to set focus... as set focus to the last of the text box character position. You can also download... are providing you a simple example to set the focus to the input text box. Not only
How do I convert a dictionary to a JSON object in Python?
How do I convert a dictionary to a JSON object in Python?  Hi, I... the dictionary object to JSON data. I want to use any pre-built API. Share me some... is returning the dictionary object. Now our requirement is to convert it to JSON
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 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 i can get jqfade.js library
how i can get jqfade.js library  how i can get jqfade.j script library
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 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 learn Java in 5 minutes
How can I learn Java in 5 minutes  Hi, I am searching for the tutorials to learn Java programming. I don't know how easy or difficult is Java.... It will be helpful for me if someone gives me tutorials to learn Java. How can I
How can I to my database to my application
How can I to my database to my application  How can I to my database to my application   Hi, Please see the JDBC discussion thread.ADS_TO_REPLACE_1 Thanks
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 can I protect my database password ?
How can I protect my database password ?   How can I protect my... in as plain text. What can I do to protect my passwords... a database over the internet. I have concerns about the security of the database
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
focus to the first form field
focus to the first form field  How do I set the focus to the first form field
focus to the first form field
focus to the first form field  How do I set the focus to the first form field
the focus to the first form field
the focus to the first form field   How do I set the focus to the first form field
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 close a frame. - Java Beginners
how can i close a frame.  Hi, My question is how can we close... frames as i go on clicking button...........can we have like when i click on button...............my target is when i click on that button, a new frame is coming and updated table
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 start big data?
How can I start big data?  Hi, I am beginner in Data Science and machine learning field. I am searching for the tutorials to learn: How can I... learn the topic "How can I start big data?". Also tell me which
How can I get IBM certification for free?
How can I get IBM certification for free?  Hi, I am beginner in Data...: How can I get IBM certification for free? Try to provide me good examples or tutorials links so that I can learn the topic "How can I get IBM
How can I practice big data at home?
How can I practice big data at home?  Hi, I am beginner in Data...: How can I practice big data at home? Try to provide me good examples or tutorials links so that I can learn the topic "How can I practice big data at home
How can I become a data scientist for free?
How can I become a data scientist for free?  Hi, I am beginner... to learn: How can I become a data scientist for free? Try to provide me good examples or tutorials links so that I can learn the topic "How can I become
How can I become a good data scientist?
How can I become a good data scientist?  Hi, I am beginner in Data...: How can I become a good data scientist? Try to provide me good examples or tutorials links so that I can learn the topic "How can I become a good data
How can I get into big data?
How can I get into big data?  Hi, I am beginner in Data Science and machine learning field. I am searching for the tutorials to learn: How can I... can learn the topic "How can I get into big data?". Also tell me
How can I learn Hadoop easily?
How can I learn Hadoop easily?  Hi, I am beginner in Data Science and machine learning field. I am searching for the tutorials to learn: How can... that I can learn the topic "How can I learn Hadoop easily?". Also tell
How can I do data science course?
How can I do data science course?  Hi, I am beginner in Data Science and machine learning field. I am searching for the tutorials to learn: How... so that I can learn the topic "How can I do data science course?"
How can I become a data scientist?
How can I become a data scientist?  Hi, I am beginner in Data Science and machine learning field. I am searching for the tutorials to learn: How... links so that I can learn the topic "How can I become a data scientist?"
How can I become a data scientist in India?
How can I become a data scientist in India?  Hi, I am beginner... to learn: How can I become a data scientist in India? Try to provide me good examples or tutorials links so that I can learn the topic "How can I become
How can I go to ISRO after BSc?
How can I go to ISRO after BSc?  Hi, I am beginner in Data Science and machine learning field. I am searching for the tutorials to learn: How can... that I can learn the topic "How can I go to ISRO after BSc?". Also
How quickly can I learn Python?
How quickly can I learn Python?  Hi, I am beginner in Data Science and machine learning field. I am searching for the tutorials to learn: How... that I can learn the topic "How quickly can I learn Python?". Also

Ads