-1

I wrote some code to create a little square on the screen, but when I press the left button, nothing seems to happen. The rectangle doesn't move, and "Move Left." doesn't get printed out in the console. Here's the code.

package game;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;

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

@SuppressWarnings({ "serial" })
public class Game extends Canvas implements Runnable, KeyListener{

    public static final int WIDTH = 400;
    public static final int HEIGHT = WIDTH/12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";
    //Size, scale, and name of window.

    boolean running = false;
    public int tickCount = 0;

    //X and Y coordinates of the rectangle on the screen.
    private static int rectX = 10;
    private int rectY = 10;

    JFrame f;
    Canvas can;
    BufferStrategy bs;

    Controls c;
public Game(){

    f = new JFrame(NAME);
    f.setSize(400, 400);
    f.setVisible(true);
    //Sets the size of the window and makes it visible.
    JPanel panel = (JPanel) f.getContentPane();
    panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    panel.setLayout(null);
    //Sets preferred size and layout to null.
    can = new Canvas();
    can.setBounds(0, 0, 400, 400);
    can.setIgnoreRepaint(true);
    //Creates new canvas.
    panel.add(can);
     //Adds the canvas to the JPanel.
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setResizable(false);
    //Makes the window packed, nonresizable, and close the program on exit.
    can.createBufferStrategy(3);
    bs = can.getBufferStrategy();
    //Creates buffer strategy for the canvas.
    System.out.println("Window created.");
    addKeyListener(this);
}

public synchronized void start(){
    running = true;
    new Thread(this).start();
    //Starts thread
}

public synchronized void stop(){
    running = false;
    //For stopping the program.
}

public void run() {
    long lastTime = System.nanoTime();
    double nsPerTick = 1000000000.0/60.0;

    int frames = 0;
    int ticks = 0;
    long lastTimer = System.currentTimeMillis();
    double delta = 0;
    while(running)
    {
        long now = System.nanoTime();
        delta += (now - lastTime)/nsPerTick;
        lastTime = now;
        boolean shouldRender = true;
        while(delta>=1)
        {
        ticks++;
        tick();
        delta -= 1;
        shouldRender = true;
        //Creates 60fps timer. Not in use.
        }
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(shouldRender)
        {
        frames++;
        render();
        //Renders the image.
        }
        if(System.currentTimeMillis() - lastTimer >= 1000)
        {
            lastTimer += 1000;
            System.out.println(frames + " frames, " + ticks + " ticks");
            frames = 0;
            ticks = 0;
            //Resets timer. Not in use.
        }
    }
}

public void tick(){
    tickCount++;
    //Not in use, yet.
}

public void render(){
    Graphics2D g = (Graphics2D)bs.getDrawGraphics();
    //Sets g to the buffer strategy bs.
    g.setColor(Color.BLACK);
    g.fillRect(rectX, rectY, 100, 100);
    //Creates black rectangle.
    g.dispose();
    bs.show();
    //Puts the rectangle on the screen.
}

public static void main(String [] args){
    new Game().start();
    //Starts thread.
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
    if(e.getKeyCode()==KeyEvent.VK_LEFT)
    {
        --rectX;
        System.out.println("Move left.");
    }

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

}

  • Looking through your code, I can see that there's more issues than just the keylistener. You aren't drawing correctly, you haven't added your listeners correctly, you are mixing AWT and Swing components... I'm sorry, but you're not really at a point where we can help you – ControlAltDel Sep 28 '14 at 01:30

1 Answers1

0

Because at your constructor, you create a new Canvas,and don't use the Game canvas and your rectangle is drawn at the new Canvas, not Game canvas, so your listener has no effect.

Please see the the follow new constructor, I tested it, it works fine.

    public Game() {

        frame = new JFrame(NAME);
        frame.setSize(400, 400);
        frame.setVisible(true);
        // Sets the size of the window and makes it visible.
        JPanel panel = (JPanel) frame.getContentPane();
        panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        panel.setLayout(null);
        // Sets preferred size and layout to null.
        //can = new Canvas();
        //can.setBounds(0, 0, 400, 400);
        //can.setIgnoreRepaint(true);
        setBounds(0, 0, 400, 400);
        setIgnoreRepaint(true);
        // Creates new canvas.
        panel.add(this);
        // Adds the canvas to the JPanel.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        // Makes the window packed, nonresizable, and close the program on exit.
        //can.createBufferStrategy(3);
        createBufferStrategy(3);
        bs = getBufferStrategy();
        // Creates buffer strategy for the canvas.
        System.out.println("Window created.");
        addKeyListener(this);
    }
Liu guanghua
  • 981
  • 1
  • 9
  • 18