Hi, I was creating clone of breakout and got the game working correctly. But after setting up menu my keyboard doesnt respond anymore. But if I launch game directly without Menu class keys are working perfectly. Where the problem might be? Here is the full source code.

VBreakOut.java

package net.viped;

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class VBreakOut {
    static JFrame frame = new JFrame(); 
    public VBreakOut() {
        int width = 800;
        int height = 640;
        frame.setTitle("vBreakOut 0.01");
        frame.setSize(width, height);
        frame.setContentPane(new Menu(this));
        frame.setBackground(Color.black);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setResizable(false);
    }



    public static void main(String[] args) {
        new VBreakOut();
    }

    public static void setContentPane(int pane) {
        switch(pane) {
        case 1:
            frame.setContentPane(new Game());
            frame.validate();
        }
    }
}

Game.java

package net.viped;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

import com.apple.mrj.macos.carbon.Timer;
import com.sun.j3d.utils.geometry.Sphere;

public class Game extends JPanel {

    private int BRICKSX = 40;
    private int BRICKSY = 5;
    int width = 800;
    int height = 640;
    BufferedImage backbuffer;
    Graphics2D g2d;
    boolean gameOn = false;
    Brick[][] bricks = new Brick[BRICKSX][BRICKSY];
    BufferedImage brickImg;
    Saie gameloop = new Saie();

    private double ballX = 250;
    private double ballY = 50;

    private int speed = 30;

    private boolean right = false;
    private boolean left = false;
    private boolean down = false;
    private boolean up = false;

    private double dx = -2;
    private double dy = -2;

    Ellipse2D ball;

    private int batx = 100;
    private int baty = 600;
    private int batWidth = 50;
    private Rectangle2D bat = new Rectangle2D.Double(batx, baty, batWidth, 10);

    private long time1;
    private long time2;
    private long time3;

    public Game() {
        requestFocus(true);
        setFocusable(true);
        addKeyListener(new ListenKeys());

        try {
            brickImg = ImageIO.read(new File("res/brick.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (int i = 0; i < BRICKSY; i++) {
            for (int j = 0; j < BRICKSX; j++) {
                bricks[j][i] = new Brick();
                bricks[j][i].setBounds(j * 40, i*20, 40, 20);
            }
        }

        initBoard();

    }

    public void initBoard() {
        backbuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        g2d = backbuffer.createGraphics();

        initGame();
        gameOn = true;
        gameloop.start();
    }

    public void initGame() {
        ball = new Ellipse2D.Double(ballX, ballY, 10, 10);
    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paint(g);
        for (int i = 0; i < BRICKSY; i++) {
            for (int j = 0; j < BRICKSX; j++) {
                if (bricks[j][i].isAlive()) {
                    g.drawImage(bricks[j][i].getImg(bricks[j][i].getState()), j * 40, i*20, this);
                    g.setColor(Color.yellow);
                } else if (!bricks[j][i].isAlive()) {
                    g.setColor(Color.black);
                    g.fillRect(j * 40, i*20, 40, 20);
                }
            }
        }
        g2d.draw(bat);
        g2d.draw(ball);
        g.setColor(Color.red);
        AffineTransform identity = new AffineTransform();
        g2d.draw(ball);

        // g.drawImage(backbuffer, 0, 0, this);
        g.dispose();
    }

    public class Saie extends Thread {
        public void run() {
            while (gameOn) {
                try {
                    Thread.sleep(speed+1);
                } catch (Exception e) {
                }
                // COLLISION DETECTION BRICKS
                for (int i = 0; i < BRICKSY; i++) {
                    for (int j = 0; j < BRICKSX; j++) {
                        if (bricks[j][i].intersects(ball.getBounds2D()) && bricks[j][i].isAlive()) {
                            dy = dy * -1;
                            if (bricks[j][i].getState() < 3) {
                                bricks[j][i].setState(bricks[j][i].getState() + 1);
                            } else {
                                bricks[j][i].setAlive(false);
                            }
                        }
                    }
                }

                // BAT CONTROLS
                if (right) {
                    batx += 3;
                    bat.setRect(batx, baty, batWidth, 10);
                }
                if (left) {
                    batx -= 3;
                    bat.setRect(batx, baty, batWidth, 10);
                }
                // BALL CONTROLLING
                if (ballX < 0) {
                    dx = dx * -1;
                }
                if (ballX > width - 10) {
                    dx = dx * -1;
                }
                if (ball.intersects(bat)) {
                    double angle = ballX/batx;
                    System.out.println(dy);
                    dy = dy * -1;
                }
                if (ballY < 0) {
                    dy = dy * -1;
                }
                ballY = ballY + dy;
                ballX = ballX + dx;
                ball.setFrame(ballX, ballY, 10, 10);
                repaint();
            }
        }
    }

    public class ListenKeys extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            if (key == e.VK_LEFT) {
                left = true;
                System.out.println("left");
            }
            if (key == e.VK_RIGHT) {
                right = true;
            }
            if (key == e.VK_UP) {
                speed--;
            }
            if (key == e.VK_DOWN) {
                speed++;
            }
            if (key == e.VK_C) {
                batWidth = 800;
            }
        }

        public void keyReleased(KeyEvent e) {
            left = false;
            right = false;
            up = false;
            down = false;
        }

        public void keyTyped(KeyEvent e) {
            int key = e.getKeyCode();

        }
    }

}

Brick.java

package net.viped;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class Brick extends Rectangle2D {
    private BufferedImage img;
    private BufferedImage subImg;
    private int state = 0;
    private boolean alive = true;
    private Graphics2D g2d;
    private JFrame frame;
    private int x;
    private int y;
    private int width = 40;
    private int height = 20;

    public Brick() {
        try {
            img = ImageIO.read(new File("res/brick.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public BufferedImage getImg(int state) {
        if (state == 0) {
            return img.getSubimage(0, 0, 40, 20);
        } else if (state == 1) {
            return img.getSubimage(60, 0, 40, 20);
        } else if (state == 2) {
            return img.getSubimage(120, 0, 40, 20);
        }

        return null;
    }

    public void setImg(Image img) {

    }

    public boolean isAlive() {
        return alive;
    }

    public BufferedImage getImg() {
        return img;
    }

    public void setImg(BufferedImage img) {
        this.img = img;
    }

    public BufferedImage getSubImg() {
        return subImg;
    }

    public void setSubImg(BufferedImage subImg) {
        this.subImg = subImg;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public Graphics2D getG2d() {
        return g2d;
    }

    public void setG2d(Graphics2D g2d) {
        this.g2d = g2d;
    }

    public void setFrame(JFrame frame) {
        this.frame = frame;
    }

    public double getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public void setAlive(boolean alive) {
        this.alive = alive;
    }

    @Override
    public Rectangle2D createIntersection(Rectangle2D arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Rectangle2D createUnion(Rectangle2D arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int outcode(double arg0, double arg1) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void setRect(double arg0, double arg1, double arg2, double arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return false;
    }

    public void setBounds(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

}

Menu.java

package net.viped;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.media.j3d.Background;
import javax.swing.JButton;
import javax.swing.JPanel;

public class Menu extends JPanel implements ActionListener{

    BufferedImage menubg;
    JButton play = new JButton("Play vBreakOut");

    public Menu(VBreakOut vbo) {

        try {
            menubg = ImageIO.read(new File("res/menubg.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        setLayout(null);

        play.setBounds(300, 200, 200, 40);
        play.addActionListener(this);
        add(play);

    }

    public void paintComponent(Graphics g) {
        g.drawImage(menubg, 0, 0, this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals(play.getText())) {
            VBreakOut.setContentPane(1);
        }
    }

}

Recommended Answers

All 10 Replies

Isnt there way to get the keyboard focus to the Game contentpane?

Yes there is:
http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html
... but when you read that multi-part tutorial you will discover that (a) it's far from easy and (b) depending on what the user does it still may not work as you want.

Trust me, it's easier to go with the subsystem designed specially to deal with all this - just follow the link from my first post and set your bindings for WHEN_IN_FOCUSED_WINDOW

Okay I trust you. I already checked link but I am not sure how it works. I guess I have to just give it a try. Thanks.

Can't get it work. Could you give me a quick tuto for key bindings?

That was the quick tuto!
I have no time now to write a new one, maybe later... ?

If you just have time. I mark the question solved if I figure it out.

Okay, somehow I managed to get it work. I am not even sure what I did. Thanks.

I have the same problem ... could you please tell me what you did to solve this ? ty

Try using key binding instead of key listeners.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.