Image flickers on repaint() - java

I figured out the solution for my previous question which landed me into new problem.
In the following code im moving an image around a JFrame using arrow keys. but every time i press an arrow key the image seems to flicker which is quite noticeable when a key is pressed continuously.
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class TestProgram extends JFrame implements KeyListener {
private BufferedImage TestImage;
private int cordX = 100;
private int cordY = 100;
public TestProgram() {
setTitle("Testing....");
setSize(500, 500);
imageLoader();
setVisible(true);
}
public void imageLoader() {
try {
String testPath = "test.png";
TestImage = ImageIO.read(getClass().getResourceAsStream(testPath));
} catch (IOException ex) {
ex.printStackTrace();
}
addKeyListener(this);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(TestImage, cordX, cordY, this);
}
public static void main(String[] args) {
new TestProgram();
}
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT: {
cordX+=5;
}
break;
case KeyEvent.VK_LEFT: {
cordX-=5;
}
break;
case KeyEvent.VK_DOWN: {
cordY+=5;
}
break;
case KeyEvent.VK_UP: {
cordY-=3;
}
break;
}
repaint();
}
public void keyTyped(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {}
}
Is there any solution to avoid that?
EDIT: above is the complete working code. I'm finding it difficult to incorporate doublebuffer in it. can anyone help me in that part?

Non flickering, working Code.
Repaint() doesn't just call the paint() method. A repaint() method actually calls the update() method and the default update() method then calls to the paint() method. So just override the update() method. Also painting as BufferedImage as mentioned above correctly.
This should work now. It worked fine here. I only used a different imagepath.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class TestProgram extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private Image TestImage;
private BufferedImage bf;
private int cordX = 100;
private int cordY = 100;
public TestProgram() {
setTitle("Testing....");
setSize(500, 500);
imageLoader();
setVisible(true);
}
public void imageLoader() {
try {
String testPath = "test.png";
TestImage = ImageIO.read(getClass().getResourceAsStream(testPath));
} catch (IOException ex) {
ex.printStackTrace();
}
addKeyListener(this);
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
bf = new BufferedImage( this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_RGB);
try{
animation(bf.getGraphics());
g.drawImage(bf,0,0,null);
}catch(Exception ex){
}
}
public void animation(Graphics g) {
super.paint(g);
g.drawImage(TestImage, cordX, cordY, this);
}
public static void main(String[] args) {
new TestProgram();
}
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT: {
cordX += 5;
}
break;
case KeyEvent.VK_LEFT: {
cordX -= 5;
}
break;
case KeyEvent.VK_DOWN: {
cordY += 5;
}
break;
case KeyEvent.VK_UP: {
cordY -= 3;
}
break;
}
repaint();
}
public void keyTyped(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
}
}

You have to use a Buffer to get rid of the flickering.
For images, there is the BufferedImage Buffer:
BufferedImage bf = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Then you draw your image to the screen like this:
g.drawImage(bf, 0, 0, null);

Related

KeyListener wont change variable

I have been working on this snake project, and dont really understand why the keylistener isnt actually changing the variable char key. I have some other examples of keylisteners, and they all work properly, but for some reason mine isnt working. Some help would be appreciated. Thanks a lot for the help.
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
public class Main extends JPanel implements Runnable {
/*
*
* SIZE OF BOARD
*
*/
static GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
static GraphicsDevice[] gs = ge.getScreenDevices();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private static final int DIM_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
private static final int DIM_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;
static JFrame frame = new JFrame();
static JPanel panel = new JPanel();
static Snake s = new Snake();
static Main main = new Main();
KeyListener listener = new Snake();
boolean black = true;
public Main() {
addKeyListener(listener);
}
#SuppressWarnings("deprecation")
public static void main(String[] args) {
//gs[0].setFullScreenWindow(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setCursor(Cursor.CROSSHAIR_CURSOR);
frame.setSize(DIM_WIDTH, DIM_HEIGHT);
frame.add(main);
frame.setVisible(true);
(new Thread(new Main())).start();
}
// paints the panel
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
/*
* Snake
*/
//Redraws Background
g2d.setColor(Color.black);
g2d.fillRect(0, 0, (int) screenSize.getWidth(), (int) screenSize.getHeight());
//Draws Border
g2d.setColor(Color.white);
g2d.fillRect(0,0, (int)screenSize.getWidth(), 1);
g2d.fillRect(0,0, 1, (int)screenSize.getHeight());
g2d.fillRect((int)screenSize.getWidth()-1, 1, 1, (int)screenSize.getHeight());
g2d.fillRect(0, (int)screenSize.getHeight()-86, (int)screenSize.getWidth(), 10);
//Draws Snake head
g2d.setColor(s.getColor());
g2d.fillRect(s.getX(), s.getY(), 30, 30);
}
// Creates Frame, and starts the game
#Override
public void run() {
while (!s.getIsDead()) {
move();
}
}
public void move() {
s.move();
s.death();
main.repaint();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Thread.interrupted()) {
return;
}
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Snake implements KeyListener {
Color c = Color.green;
//Starting position of Snake
int x = 50;
int y = 50;
char key;
boolean dead = false;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public void move() {
x++;
}
public void death() {
if (x + 30 >= screenSize.getWidth() || y + 115 >= screenSize.getHeight() || y<=0 || x<=0) {
c = Color.red;
dead = true;
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Color getColor() {
return c;
}
public boolean getIsDead() {
return dead;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
key = 'w';
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Change your constructor to
public Main() {
addKeyListener(listener);
setFocusable(true);
requestFocus();
}
But take a look at this question, you should not use KeyListeners.
java keylistener not called
As #azurefrog mentioned, your keyPressed method is setting key to 'w' every time. You need to use the KeyEvent passed in as a parameter to that method to get the key that was pressed. Your keyPressed method should look something like this:
#Override
public void keyPressed(KeyEvent e) {
key = e.getKeyChar();
}

Java applet in JFrame graphics glitch?

So I am trying to make a pinball game made as a applet load into a JFrame. The applet loads into it no problem but when i run it flickers and glitch out. Thanks in advance!
Jframe class:
import javax.swing.*;
import java.awt.*;
import java.applet.*;
public class PinBallGUI extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Pinball");
frame.setVisible(true);
frame.setSize(600,700);
int height = 700;
int width = 600;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PinBallGame temp = new PinBallGame();
frame.add(temp);
temp.init(width,height);
temp.start();
temp.run();
}
}
Applet class:
import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class PinBallGame extends Applet implements Runnable
{
Thread runner;
private Image Buffer;
private Graphics gBuffer;
int width,height;
PinBallBall B1;
PinBallPaddle P1,P2;
PinBallRectangle R1,R2,R3,R4;
PinBallRectangle[] rArray;
boolean leftKey;
boolean rightKey;
boolean downKey;
boolean spaceKey;
int points;
Random gen = new Random();
public void init(int W,int H)
{
width=W;
height=H;
Buffer=createImage(width,height);
gBuffer=Buffer.getGraphics();
B1 = new PinBallBall(-1,width-57,645);
P1 = new PinBallPaddle(180,625,255,640);
P2 = new PinBallPaddle(300,640,375,625);
R1 = new PinBallRectangle(1,width-35,60,15,600);
R2 = new PinBallRectangle(1,width-80,60,15,600);
R3 = new PinBallRectangle(1,0,625,180,40);
R4 = new PinBallRectangle(1,375,625,140,40);
rArray = new PinBallRectangle[5];
for(int i=0; i<rArray.length; i++)
{
rArray[i] = new PinBallRectangle(-1,gen.nextInt(450),gen.nextInt(450),gen.nextInt(60),gen.nextInt(60));
}
int count = 0;
addKeyListener(new MyKeyListener());
points = 0;
}
private class MyKeyListener extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_LEFT:
leftKey = true;
break;
case KeyEvent.VK_RIGHT:
rightKey = true;
break;
case KeyEvent.VK_SPACE:
spaceKey = true;
break;
case KeyEvent.VK_DOWN:
downKey = true;
break;
}
}
public void keyReleased(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_LEFT:
leftKey = false;
break;
case KeyEvent.VK_RIGHT:
rightKey = false;
break;
case KeyEvent.VK_SPACE:
spaceKey = false;
break;
case KeyEvent.VK_DOWN:
downKey = false;
break;
}
}
}
public void start()
{
if (runner == null)
{
runner = new Thread (this);
runner.start();
}
}
public void stop()
{
runner = null;
}
public void run()
{
while(true)
{
update(gBuffer);
if(leftKey){P1.moveLeftPaddle();}
if(rightKey){P2.moveRightPaddle();}
if(downKey){B1.launchBall(width,height);}
repaint();
try {runner.sleep(25);}
catch (Exception e) { }
repaint();
gBuffer.setColor(Color.black);
gBuffer.fillRect(0,0,width,height);
if((B1.getX() != width-57)||(B1.getY() != 645))
{
B1.movePinBallBall(width,height);
B1.update();
}
R1.ballCollision(B1);
repaint();
R2.ballCollision(B1);
repaint();
R3.ballCollision(B1);
repaint();
R4.ballCollision(B1);
repaint();
P1.ballCollision(B1);
repaint();
P2.ballCollision(B1);
repaint();
for(int i=0; i<rArray.length; i++)
{
rArray[i].ballCollision(B1);
repaint();
}
for(int i=0; i<rArray.length; i++)
{
rArray[i].paint(gBuffer);
}
update(gBuffer);
B1.paint(gBuffer);
R1.paint(gBuffer);
R2.paint(gBuffer);
R3.paint(gBuffer);
R4.paint(gBuffer);
P1.paint(gBuffer);
P2.paint(gBuffer);
repaint();
update(gBuffer);
}//while(true)
} //run
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
g.drawImage(Buffer,0,0, this);
}
}
I also have 3 other classes that are just for objects (ball, rectangle, paddle).
Thanks again in advance!
You're going to want to either use JFrame and JPanel or Frame and Canvas instead of using a JFrame and an Applet. You can definitely mix and match components, but you'll probably encounter less bugs if you don't.
I generally find flickering to happen when you aren't using double buffering. Fro a JPanel you'll want to enable double buffering and for a Canvas there is a way to implement triple buffering if you really need to, but stick with a JPanel for most cases.

java - KeyListener fails to detect collision (platformer game)

I am making a Java game, completely free of any external libraries or engines. Everything is doing fine, but I encountered a problem with the KeyListener. I do not understand why this is happening.
Whenever I animate the Character, which is extending Object (another custom class I coded) with velX, and with custom collision detection it works fine, and the Character stops moving whenever the Character Object collides with the Block Object; i.e.
ObjectController
Character c = new Character();
Character (extends Object)
public void checkCollision(LinkedList<Object> objects){
for (int i = 0; i < objects.size(); i++) {
if(this.bounds.getRCol().intersects(objects.get(i).bounds.getLCol())){
setVelX(0);
}
}
}
Object
public void tick(LinkedList<Object> objects){
x += velX;
y += velY;
checkCollision(objects)
}
KeyListener (working version, but I want the animation to stop after key is released)
public void keyPressed(KeyEvent e){
c.setVelX(1);
}
public void keyReleased(KeyEvent e){
// nothing
}
KeyListener (this version works, the animation starts when key pressed, stops when key is released, but the collision detection doesn't work)
public void keyPressed(KeyEvent e){
c.setVelX(1);
}
public void keyReleased(KeyEvent e){
c.setVelX(0);
}
I have programmed every class correctly, or at least I feel so. The right and left collision rectangles are correctly placed on all of the Objects.
So why isn't this working? Am I doing it wrong? Or is it Swing's KeyListener's fault?
Any help would be greatly appreciated. If you need more information, please comment below and I would love to put more information!
Thanks, ProgrammersDude.
EDIT - Update 1
There is a class called Panel.class, based on JPanel It is the main container of all panels.
Then there is a Subpanel.class, which extends JPanel, too. It is an abstract class and inside of that class the tick() is called.
package com.platformer.main;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public abstract class Subpanel extends JPanel implements Runnable{
private static final long serialVersionUID = 1L;
public boolean loaded = false;
public Thread loop = null;
public Subpanel(){
this.setFocusable(true);
this.requestFocusInWindow();
init();
loop = new Thread(this);
loop.start();
}
public void init(){
load();
loaded = true;
}
public abstract void load();
public void run(){
while(loaded){
tick();
repaint();
try{
Thread.sleep(17);
}catch(InterruptedException e){
}
}
}
public abstract void tick();
BufferedImage buffer;
Graphics bg;
public void paint(Graphics g){
buffer = (BufferedImage) this.createImage(Start.WIDTH, Start.HEIGHT);
bg = buffer.getGraphics();
paintComponent(bg);
g.drawImage(buffer, 0, 0, null);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(loaded){
render(g2);
}
}
public abstract void render(Graphics2D g);
}
}
Inside of the Gamepanel.class looks like this:
package com.platformer.subpanels;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import com.platformer.input.GameKeys;
import com.platformer.main.Start;
import com.platformer.main.Subpanel;
import com.platformer.objects.ObjectController;
public class Gamepanel extends Subpanel{
private static final long serialVersionUID = 1L;
ObjectController objectController;
GameKeys key;
public void load(){
objectController = new ObjectController();
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
objectController.character.setVelX(1);
}
public void keyReleased(KeyEvent e) {
objectController.character.setVelX(0);
}
});
}
public void tick(){
objectController.tick();
}
public void render(Graphics2D g){
g.setColor(Color.black);
g.fillRect(0, 0, Start.WIDTH, Start.HEIGHT);
objectController.render(g);
}
}
The GameKeys is the KeyListener that I was previously using. Now in the code as you see, I am using a custom KeyAdapter to test it out. It still doesn't work.
The GameKeys.class looks like this:
package com.platformer.input;
import java.awt.event.KeyEvent;
import com.platformer.objects.ObjectController;
import com.platformer.subpanels.Gamepanel;
public class GameKeys extends KeyInput{
private ObjectController objectController;
private com.platformer.objects.Character character;
public GameKeys(Gamepanel panel, ObjectController objectController){
super(panel);
this.objectController = objectController;
this.character = this.objectController.character;
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_ESCAPE:
System.exit(0);
case KeyEvent.VK_RIGHT:
character.setVelX(1);
}
}
public void keyReleased(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:
character.setVelX(0);
}
}
public void keyTyped(KeyEvent e) {
}
}
and it's based on KeyInput.class:
package com.platformer.input;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public abstract class KeyInput implements KeyListener{
public KeyInput(JPanel panel){
panel.addKeyListener(this);
}
}
I found a sort-of workaround. I added a simple boolean,
public void isCollision(){
return collision;
}
and a collision object that fits into:
for (int i = 0; i < objects.size(); i++) {
if(this.bounds.getRCol().intersects(objects.get(i).bounds.getLCol())){
collision = true;
setVelX(0);
}else{collision = false;}
}
Then this was modified from the GameKeys.class:
public void keyPressed(KeyEvent e){
if(!objectController.character.isCollision()){
objectController.character.setVelX(1);
}
}

How do I get my image to follow my mouse?

How do I get my image to follow my mouse anywhere on the screen?
The below code makes the image move along the x axis.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class PlayerTwo implements KeyListener, MouseListener, MouseMotionListener{
public static int PLAYER_HEIGHT = 15;
public static int PLAYER_WIDTH = 15;
private Image p2Image = null;
private static int x = 0;
private static int y = 0;
private int heightPosition = 0;
Main main = null;
public PlayerTwo(Image pi, Main m ){
main = m;
p2Image = pi;
y = (int)((Main.WIDTH*2)+(PLAYER_WIDTH*2));
heightPosition = Main.HEIGHT-PLAYER_HEIGHT-20;
}
public void drawPlayer(Graphics g){
g.drawImage(p2Image, y, heightPosition, main);
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent me) {
int newX = me.getX();
int newY = me.getY();
if(newY > (Main.HEIGHT+PLAYER_HEIGHT+10)){
y = Main.HEIGHT+PLAYER_HEIGHT+10;
}else{
y = newY;
}
// if (newX > (Main.WIDTH-PLAYER_WIDTH-10)){
// x = Main.WIDTH-PLAYER_WIDTH-10;
// }else{
// x = newX;
// }
}
}
Updated with Main...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Main extends JFrame implements Runnable {
public static int WIDTH = 600;
public static int HEIGHT = 600;
private int gameSpeed = 100;
PlayerOne playOne = null;
PlayerTwo playTwo = null;
Image p1Image = null;
Image p2Image = null;
Image backImage = null;
Graphics offscreen_high;
BufferedImage offscreen;
public Main(String frameTitle) {
super(frameTitle);
p1Image = new javax.swing.ImageIcon("src/resources/player1.gif").getImage();
p2Image = new javax.swing.ImageIcon("src/resources/player2.gif").getImage();
backImage = new javax.swing.ImageIcon("src/resources/back.png").getImage();
offscreen = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
offscreen_high = offscreen.createGraphics();
playOne = new PlayerOne(p1Image, this);
playTwo = new PlayerTwo(p2Image, this);
addKeyListener(playOne);
addKeyListener(playTwo);
addMouseListener(playTwo);
addMouseMotionListener(playTwo);
setSize(WIDTH, HEIGHT);
setVisible(true);
startGame();
}
public void startGame() {
Thread thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
offscreen_high.setColor(Color.black);
offscreen_high.fillRect(0, 0, WIDTH, HEIGHT);
offscreen_high.drawImage(backImage, 0, 0, this);
playOne.drawPlayer(offscreen_high);
playTwo.drawPlayer(offscreen_high);
g.drawImage(offscreen, 0, 0, this);
}
// public void update(Graphics g){
// paint(g);
// }
public void run() {
int count = 0;
while (true) {
try {
Thread.sleep(gameSpeed);
} catch (InterruptedException ie) {
}
repaint();
count++;
}
}
public static void main(String[] args) {
Main main = new Main("Game On!");
}
}
Generally, you need some way to tell the UI that it should be updated.
Assuming that Main is some kind of component (and it's also responsible for painting the Player), you should be calling its repaint method in the mouseListener
But without more details, this is more of a guess
Updated
After a muck around with the code, the main problem, as I see it, is your trying to draw the image only the horizontal axis (x) using the vertical position (y)...
public void drawPlayer(Graphics g){
//g.drawImage(p2Image, y, heightPosition, main);
g.drawImage(p2Image, x, heightPosition, main);
}
To get it to work, you're going to have to uncomment the code in you mouseMoved method so that the x position updates.
You should also avoid painting to top level containers, the main reason (apart from the fact that you can screw up the paint process) is that top level containers are not double buffered.
Instead, you should move your entire game container over to something like a JPanel and override it's paintComponent method (and don't for get to call super.paintComponent)

stuck on trying to implement KeyListener

I'm having a lot of trouble trying to make my code move a player (Ship) around a screen. I can get the planets to draw on the screen and the the player ship but I can not figure out how to implement the keyListener to at least print out something. Thank you in advance for all the help!
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class MapPanel extends JPanel {
public static final int WIDTH = 25;
public static final int HEIGHT = 20;
int zone = 0;
private int xValue;
private int yValue;
private Color color;
public Planet[][] planetGrid = new Planet[WIDTH][HEIGHT];
static Player currPlayer = new Player("h");
static Universe universe = new Universe(currPlayer);
/**
* Create the panel.
*/
public MapPanel(Universe univ, Player p) {
this.universe = univ;
currPlayer = p;
int i = 0;
this.setSize(new Dimension(450,450));
setVisible( true );
//this.addKeyListener(new KeyController());
KeyController kc = new KeyController();
this.addKeyListener(kc);
repaint();
}
/**
* Draw method to draw the playing field
* #param g Graphics object
* #param tileDimension dimension of the tile
*/
public void draw(Graphics g)
{
universe.draw(g);
// KeyController key = new KeyController();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public static void main(String[] args)
{
MapPanel mp = new MapPanel(universe, currPlayer);
JFrame f = new JFrame();
f.add(mp);
f.setSize(new Dimension(450,450));
f.setVisible(true);
f.setFocusable(true);
}
private class KeyController implements KeyListener {
public KeyController()
{
System.out.println("ghgh");
setFocusable(true);
// addKeyListener(this);
}
#Override
public void keyPressed(final KeyEvent key) {
System.out.println("fgfgf");
if (currPlayer != null) {
int oldX = currPlayer.getPosition().x;
int oldY = currPlayer.getPosition().y;
switch (key.getKeyCode()) {
case KeyEvent.VK_RIGHT:
currPlayer.setPosition(new Point(oldX+1, oldY)); //move right
System.out.println("RIGHT");
break;
case KeyEvent.VK_LEFT:
currPlayer.setPosition(new Point(oldX-1, oldY)); //move left
break;
case KeyEvent.VK_DOWN:
currPlayer.setPosition(new Point(oldX, oldY+1)); //move down
break;
case KeyEvent.VK_UP:
currPlayer.setPosition(new Point(oldX, oldY-1)); //move up
break;
}
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("ggg");
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("typeeeddd");
}
}
}
A JPanel won't get its keyboard focus automatically, you should call this, in the constructor:
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent evt){
requestFocus();
}
});
You may have to do
MapPanel panel = new MapPanel();
panel.setFocusable(true);
I was having the same problem, and I had to do for all the other components (such as JButton's) the following:
myButton.setFocusable(false);
Worked for me.

Categories

Resources