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
Advertisements
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 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... in the JSON document.
I want to the easy way to convert the dictionary
object... is returning the dictionary
object.
Now our requirement is to convert it to JSON
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 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 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 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 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 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 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 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