简体   繁体   中英

Java Graphic2D Issue in creating Pacman

It's summer so I thought to teach myself a little bit more so I started to create a pacman game but I'm having an issue just in beginning.

public class PacMan {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {

    GameApp runapp = new GameApp();

    runapp.run();
}

}

class GameApp

public class GameApp {  
    public void run() throws IOException {

        GameCanvas game = new GameCanvas();
        PacPlay play = new PacPlay();
        JFrame frame = new JFrame(game.getTitle());
        frame.setSize(game.getWidth(), game.getHeight());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(play);
    } 
} 

other class

public class PacPlay extends JPanel implements ActionListener , KeyListener {

    int X , Y = 0 ;
    int KeyCode ;

    BufferedImage PacUP ;
    BufferedImage PacDOWN ;
    BufferedImage PacLEFT ;
    BufferedImage PacRIGHT ;  

    public PacPlay() throws IOException {
        PacRIGHT = ImageIO.read(new File("images\\right.GIF"));
    }

    public void PaintComponent(Graphics2D g) {
        g.drawImage(PacRIGHT , X, Y , null);
    }

    @Override
    public void keyPressed(KeyEvent ke) {
        KeyCode = ke.getKeyCode();
    }
}

All I get here is just an empty frame. Where am I going wrong?

setVisible should be called after all components have been added to the frame. Also Java is case sensitive, so its

@Override 
public void paintComponent(Graphics g) { // note Graphics instead of Graphics2D 
   super.paintComponent(g);
   g.drawImage(pacRightImage, x, y, this);
}

when doing custom painting. Remember to invoke super.paintComponent(g) to paint background components

Read: Performing Custom Painting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM