Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners how can i set an object in focus
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


Ankush Pruthi
how can i set an object in focus
0 Answer(s)      a year ago
Posted in : Java Beginners


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


Advertisement
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...: Choose Polygonal lasso tool (L key) to make selection of the object. Blur
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
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
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
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
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 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 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 make monthly register ?
how can i make monthly register ?  how can i make monthly register ? iam using jdeveloper
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 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 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 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. Thanks
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 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 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 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 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 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 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 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 we find the number of rows in a result set using PHP?
How can we find the number of rows in a result set using PHP?   How can we find the number of rows in a result set using PHP
how can i simplify my java code
how can i simplify my java code  /* Create a program that prompts... c=0;int f=0;int i=0; int counter=0; int starter=0; int cot=1...)(Math.random() * 9 +cot); h = (int)(Math.random() * 9 +counter); i = (int
Advertisements
 

 

 

DMCA.com