Visualizzazione dei risultati da 1 a 8 su 8
  1. #1

    Non funziona il KeyListener in Java.

    Ciao a tutti, sto cercando di fare un gioco molto semplice in java, per muovere il giocatore ho inserito un keylistener, purtroppo però non funziona. Ho già usato i keylistener altre volte, ma questa volta non riesco proprio a capire come funziona. Ecco il codice:

    codice:
    public class Game extends JPanel implements KeyListener {
        
        private String ibackgroundpath = "/images/background.png";
        private String ibackground1path = "/images/background1.png";
        private String iplayerpath = "/images/player.png";
        private int bgx = 0, bgy = 0, bg1x = 0, bg1y = bgy - Main.HEIGHT;
        private int playerx = 360, playery = 400, velX = 0, velY = 0;
        public boolean up = false, down = false, left = false, right = false;
    
    
        public void paint(Graphics g) {}
    
    
        public Image getBackgroundImage() {}
    
    
        public Image getBackground1Image() {}
    
    
        public Image getPlayerImage() {}
    
    
        public void moveBackground() {}
        
        public void movePlayer(){
            if(up){
                velY = -2;
            }
            if(down){
                velY = 2;
            }
            if(right){
                velX = 2;
            }
            if(left){
                velX = -2;
            }
        }
        
        @Override
        public void keyPressed(KeyEvent e) {
        
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_W) {
                up = true;
            }
            if (key == KeyEvent.VK_S) {
                down = true;
            }
            if (key == KeyEvent.VK_A) {
                left = true;
            }
            if (key == KeyEvent.VK_D) {
                right = true;
            }
        }
    
    
        @Override
        public void keyReleased(KeyEvent e) {
            
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_W) {
                up = false;
            }
            if (key == KeyEvent.VK_S) {
                down = false;
            }
            if (key == KeyEvent.VK_A) {
                left = false;
            }
            if (key == KeyEvent.VK_D) {
                right = false;
            }
        }
    
    
        @Override
        public void keyTyped(KeyEvent e) {}
        
        public void update() {
            addKeyListener(this);
            setFocusable(true);
            moveBackground();
            movePlayer();
            
            playerx += velX;
            playery += velY;
        }
    }
    Non so se possa servire ma sto usando un CardLayout per passare dal menu al gioco quando viene cliccato il bottone play nel menu.

    Sapete quale potrebbe essere il problema?
    Grazie in anticipo

  2. #2
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,315
    Java viene trattato nel forum "Java".

    Sposto.


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  3. #3
    Utente di HTML.it L'avatar di Alex'87
    Registrato dal
    Aug 2001
    residenza
    Verona
    Messaggi
    5,802
    In teoria il listener rileva l'evento se il componente su cui si trova ha il focus... E se non sbaglio JPanel è un componente passivo
    SpringSource Certified Spring Professional | Pivotal Certified Enterprise Integration Specialist
    Di questo libro e degli altri (blog personale di recensioni libri) | ​NO M.P. TECNICI

  4. #4
    Scusate se l'ho messo nella sezione sbagliata ma mi sono appena iscritto

    Non sono sicuro che sia passivo, ma non ricordo bene...
    Comunque ho usato molte altre volte il keylistener con una classe JPanel e ha sempre funzionato...

    Nella funzione update() ho messo: setFocusable(true); per dargli il focus, come ho sempre fatto...

  5. #5
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,281
    Quote Originariamente inviata da TheCazziator33 Visualizza il messaggio
    Ecco il codice:
    Sapete quale potrebbe essere il problema?
    Innanzitutto il codice è un po' vago .... si vedono molti metodi "vuoti" (pure il paint "ufficiale" del painting) e non si capisce il perché. Quel update() non si sa chi/quando lo invoca ....

    Comunque un JPanel per default non riceve il focus ma può essere "focusable" se si invoca setFocusable(true);
    Ad ogni modo, anche ammesso che il KeyListener sia correttamente registrato, quei keyPressed/keyReleased cambiano solo delle variabili e null'altro .... quindi non so cosa ti aspetti ....
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  6. #6
    I metodi "vuoti" nel mio codice non sono vuoti, qui li ho scritti così perchè non volevo scrivere una cosa troppo lunga che poi non si capisce niente... keyPressed e keyReleased cambiano dei valori che nel void movePlayer() vengono usati per far muovere il giocatore...

    Comunque ora posto tutto il codice:

    Questa è la classe principale (Main.java):
    codice:
    import java.awt.CardLayout;
    
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    
    public class Main {
        
        public static int WIDTH = 1920, HEIGHT = WIDTH / 16 * 9;
        public static boolean playing = false;
    
    
        public static void main(String[] args) throws InterruptedException{
            Menu menu = new Menu();
            Game game = new Game();
            
            CardLayout cl = new CardLayout();
            JPanel panel = new JPanel();
            panel.add(menu, "1");
            panel.add(game, "2");
            panel.setLayout(cl);
            
            JFrame f = new JFrame("Game Walking");
            f.setSize(WIDTH, HEIGHT);
            f.add(panel);
            f.setResizable(false);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            while(true){
                if(!playing){
                    cl.show(panel, "1");
                    menu.update();
                    menu.repaint();
                }else{
                    cl.show(panel, "2");
                    game.update();
                    game.repaint();
                }
                Thread.sleep(10);
            }
        }
    }

    Questa è la classe del menu (Menu.java):

    codice:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.MouseInfo;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    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;
    
    
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    
    
    
    
    public class Menu extends JPanel implements MouseListener, MouseMotionListener{
        
        public String imenupath = "/images/menu.png";
        public String imenuselectionpath = "/images/menuselection.png";
        public int mousex, mousey;
        public boolean isPlaySelected = false, isExitSelected = false;
        
        public void paint(Graphics g){
            super.paint(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawImage(getMenuImage(), 0, 0, Main.WIDTH, Main.HEIGHT, null);
            g2d.setColor(Color.red);
            if(isPlaySelected){
                g2d.drawImage(getMenuSelectionImage(), (Main.WIDTH*165)/1000, (Main.HEIGHT*148)/562, (Main.WIDTH*75)/1000, (Main.HEIGHT*50)/562, null);
            }
            if(isExitSelected){
                g2d.drawImage(getMenuSelectionImage(), (Main.WIDTH*545)/1000, (Main.HEIGHT*348)/562, (Main.WIDTH*75)/1000, (Main.HEIGHT*50)/562, null);
            }
            //g2d.drawRect((Main.WIDTH*149)/1000, (Main.HEIGHT*99)/562, (Main.WIDTH*302)/1000, (Main.HEIGHT*135)/562);
            //g2d.drawRect((Main.WIDTH*530)/1000, (Main.HEIGHT*298)/562, (Main.WIDTH*302)/1000, (Main.HEIGHT*137)/562);
        }
        
        public Image getMenuImage(){
            ImageIcon imenu = new ImageIcon(getClass().getResource(imenupath));
            return imenu.getImage();
        }
        
        public Image getMenuSelectionImage(){
            ImageIcon imenuselection = new ImageIcon(getClass().getResource(imenuselectionpath));
            return imenuselection.getImage();
        }
        
        public void cursorInButton(){
            Rectangle rplay = new Rectangle((Main.WIDTH*149)/1000, (Main.HEIGHT*99)/562, (Main.WIDTH*302)/1000, (Main.HEIGHT*135)/562);
            Rectangle rexit = new Rectangle((Main.WIDTH*530)/1000, (Main.HEIGHT*298)/562, (Main.WIDTH*302)/1000, (Main.HEIGHT*137)/562);
            
            if(rplay.contains(mousex, mousey)){
                isPlaySelected = true;
            }else{
                isPlaySelected = false;
            }
            if(rexit.contains(mousex, mousey)){
                isExitSelected = true;
            }else{
                isExitSelected = false;
            }
        }
        
        public void update(){
            addMouseMotionListener(this);
            setFocusable(true);
            addMouseListener(this);
            setFocusable(true);
            
            cursorInButton();
        }
    
    
        @Override
        public void mouseClicked(MouseEvent e) {
            if(e.getButton() == 1 && isPlaySelected){
                Main.playing = true;
            }
            if(e.getButton() == 1 && isExitSelected){
                System.exit(0);
            }
        }
    
    
        @Override
        public void mouseEntered(MouseEvent e) {}
    
    
        @Override
        public void mouseExited(MouseEvent e) {}
    
    
        @Override
        public void mousePressed(MouseEvent e) {}
    
    
        @Override
        public void mouseReleased(MouseEvent e) {    }
    
    
        @Override
        public void mouseDragged(MouseEvent e) {}
    
    
        @Override
        public void mouseMoved(MouseEvent e) {
            mousex = e.getX();
            mousey = e.getY();
        }
    }
    Questa è la classe del gioco vero e proprio (Game.java):

    codice:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    
    
    public class Game extends JPanel implements KeyListener {
        
        private String ibackgroundpath = "/images/background.png";
        private String ibackground1path = "/images/background1.png";
        private String iplayerpath = "/images/player.png";
        private int bgx = 0, bgy = 0, bg1x = 0, bg1y = bgy - Main.HEIGHT;
        private int playerx = 360, playery = 400, velX = 0, velY = 0;
        public boolean up = false, down = false, left = false, right = false;
    
    
        public void paint(Graphics g) {
            super.paint(g);
    
    
            Graphics2D g2d = (Graphics2D) g;
    
    
            g2d.drawImage(getBackgroundImage(), bgx, bgy, Main.WIDTH, Main.HEIGHT,
                    null);
            g2d.drawImage(getBackground1Image(), bg1x, bg1y, Main.WIDTH,
                    Main.HEIGHT, null);
            g2d.drawImage(getPlayerImage(), (Main.WIDTH * playerx) / 1000,
                    (Main.HEIGHT * playery) / 562, (Main.WIDTH * 75) / 1920,
                    (Main.HEIGHT * 150) / 1080, null);
        }
    
    
        public Image getBackgroundImage() {
            ImageIcon ibackground = new ImageIcon(getClass().getResource(
                    ibackgroundpath));
            return ibackground.getImage();
        }
    
    
        public Image getBackground1Image() {
            ImageIcon ibackground1 = new ImageIcon(getClass().getResource(
                    ibackground1path));
            return ibackground1.getImage();
        }
    
    
        public Image getPlayerImage() {
            ImageIcon iplayer = new ImageIcon(getClass().getResource(iplayerpath));
            return iplayer.getImage();
        }
    
    
        public void moveBackground() {
            bgy += 2;
            bg1y += 2;
            if (bgy >= Main.HEIGHT) {
                bgy = bg1y - Main.HEIGHT;
            }
            if (bg1y >= Main.HEIGHT) {
                bg1y = bgy - Main.HEIGHT;
            }
        }
        
        public void movePlayer(){
            if(up){
                velY = -2;
            }
            if(down){
                velY = 2;
            }
            if(right){
                velX = 2;
            }
            if(left){
                velX = -2;
            }
        }
        
        @Override
        public void keyPressed(KeyEvent e) {
        
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_W) {
                up = true;
            }
            if (key == KeyEvent.VK_S) {
                down = true;
            }
            if (key == KeyEvent.VK_A) {
                left = true;
            }
            if (key == KeyEvent.VK_D) {
                right = true;
            }
        }
    
    
        @Override
        public void keyReleased(KeyEvent e) {
            
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_W) {
                up = false;
            }
            if (key == KeyEvent.VK_S) {
                down = false;
            }
            if (key == KeyEvent.VK_A) {
                left = false;
            }
            if (key == KeyEvent.VK_D) {
                right = false;
            }
        }
    
    
        @Override
        public void keyTyped(KeyEvent e) {}
        
        public void update() {
            addKeyListener(this);
            setFocusable(true);
            moveBackground();
            movePlayer();
            
            playerx += velX;
            playery += velY;
        }
    }

  7. #7
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,281
    Quote Originariamente inviata da TheCazziator33 Visualizza il messaggio
    Comunque ora posto tutto il codice:
    Ora che lo vedo tutto ....... beh, sinceramente sono un po' imbarazzato nel rispondere. Ci sono talmente tante cose sbagliate / inappropriate / non "belle" / dubbie che .... non saprei da dove partire .....
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  8. #8
    Si bhe diciamo che ho iniziato a programmare da poco... Ho seguito vari tutorial su youtube e ho cercato di metterli assieme... Vorrei solo sapere perchè non funziona il keylistener che ha sempre funzionato, non sono sicuro ma credo ci sia qualche problema con il CardLayout...

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.