Foros del Web » Programación para mayores de 30 ;) » Java »

KeyListener deja de funcionar

Estas en el tema de KeyListener deja de funcionar en el foro de Java en Foros del Web. Buenas noches, Estoy programando un juego y tengo un problema. Al cambiar de JPanel, el KeyListener del segundo JPanel no funciona porque la nave no ...
  #1 (permalink)  
Antiguo 04/05/2013, 19:30
 
Fecha de Ingreso: mayo-2013
Ubicación: Madrid
Mensajes: 4
Antigüedad: 10 años, 11 meses
Puntos: 0
KeyListener deja de funcionar

Buenas noches,

Estoy programando un juego y tengo un problema. Al cambiar de JPanel, el KeyListener del segundo JPanel no funciona porque la nave no se mueve ni dispara. Invocando directamente al segundo JPanel si que funciona.

¿Que puede suceder, como puedo solventarlo? Adjunto el código en los siguientes mensajes. ¿Puede ayudarme alguien?

Muchas gracias,
Un saludo
  #2 (permalink)  
Antiguo 04/05/2013, 19:30
 
Fecha de Ingreso: mayo-2013
Ubicación: Madrid
Mensajes: 4
Antigüedad: 10 años, 11 meses
Puntos: 0
Información Respuesta: KeyListener deja de funcionar

Código:
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.MouseListener;
import javax.swing.*; 
import java.net.URL;

public class RType extends JFrame
{
    private JPanel menuInicial;
    
    public RType() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        muestraMenu();
    }
    
    public void muestraMenu()
    {
        menuInicial = new MenuInicial();
        this.add(menuInicial, BorderLayout.CENTER);
        this.pack();
        this.setSize(550, 550);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    
    public static void main(String [] args)
    {
        RType gameInstance = new RType();
    }
}
  #3 (permalink)  
Antiguo 04/05/2013, 19:31
 
Fecha de Ingreso: mayo-2013
Ubicación: Madrid
Mensajes: 4
Antigüedad: 10 años, 11 meses
Puntos: 0
Información Respuesta: KeyListener deja de funcionar

Código:
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.MouseListener;
import javax.swing.*; 
import java.net.URL;

/**
 * Write a description of class MenuInicial here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class MenuInicial extends JPanel
{
    private JLabel imgFacil = new JLabel();
    private JLabel imgNormal = new JLabel();
    private JLabel imgImposible = new JLabel();
    private JLabel imgComplicado = new JLabel();

    private static final int POSICION_X = 100;
    private static final int POSICION_FACIL = 100;
    private static final int POSICION_NORMAL = 200;
    private static final int POSICION_COMPLICADO = 300;
    private static final int POSICION_IMPOSIBLE = 400;
    
    /**
     * Constructor for objects of class MenuInicial
     */
    public MenuInicial()
    {
        Toolkit t = Toolkit.getDefaultToolkit();
        setSize(550, 550);
        setLayout(null);
        
        imgFacil.setIcon(new ImageIcon("Images/Facil.jpg"));
        imgFacil.addMouseListener(new MyMouseListener());
        imgFacil.setName("Facil");
        add(imgFacil);
        imgFacil.setBounds(POSICION_X, POSICION_FACIL, 261, 65);
        
        imgNormal.setIcon(new ImageIcon("Images/Normal.jpg"));
        imgNormal.addMouseListener(new MyMouseListener());
        add(imgNormal);
        imgNormal.setBounds(POSICION_X, POSICION_NORMAL, 261, 65);
        
        imgComplicado.setIcon(new ImageIcon("Images/Complicado.jpg"));
        imgComplicado.addMouseListener(new MyMouseListener());
        add(imgComplicado);
        imgComplicado.setBounds(POSICION_X, POSICION_COMPLICADO, 261, 65);
        
        imgImposible.setIcon(new ImageIcon("Images/Imposible.jpg"));
        imgImposible.addMouseListener(new MyMouseListener());
        add(imgImposible);
        imgImposible.setBounds(POSICION_X, POSICION_IMPOSIBLE, 261, 65);
    }

    public void iniciaJuego(int nivel)
    {
        JFrame frame = (JFrame)this.getTopLevelAncestor();
        frame.remove(this);
        frame.add(new Ventana(nivel), BorderLayout.CENTER);
        frame.pack();
        frame.setSize(1000, 550);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    public class MyMouseListener extends MouseAdapter
    {
        public void mouseClicked(MouseEvent e)
        {
            JLabel origen = (JLabel)e.getSource();
            if(origen.getName() == "Facil")
            {
                System.out.println("Hola");
                iniciaJuego(1); 
            }
            if(origen.getName() == "Normal")
            {
                //iniciaJuego(2); 
            }
            if(origen.getName() == "Complicado")
            {
                //iniciaJuego(3); 
            }
            if(origen.getName() == "Imposible")
            {
                //iniciaJuego(4); 
            }
        }
        
        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }
    }
}
  #4 (permalink)  
Antiguo 04/05/2013, 20:24
 
Fecha de Ingreso: mayo-2013
Ubicación: Madrid
Mensajes: 4
Antigüedad: 10 años, 11 meses
Puntos: 0
Información Respuesta: KeyListener deja de funcionar

Código:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.Image;

import java.util.Iterator;
import java.util.ArrayList;

import javax.swing.Timer;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;


/**
 * Write a description of class MenuInicial2 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Ventana extends JPanel implements ActionListener 
{   
    /*****************************
     * Declaration Variable Zone *
     *****************************/
    private int level = 0;
    private int counter = 0;
     
    /***************************
     * Declaration Object Zone *
     ***************************/
    Background background;
    Spacecraft spacecraft;
    ArrayList<MartianGroup1> martianGroup1;
    ArrayList<MartianGroup2> martianGroup2;
    ArrayList<MartianGroup3> martianGroup3;
    ArrayList<MartianGroup4> martianGroup4;
    
    /********************
     * Auxiliar Objects *
     ********************/
    Timer timer;
    
    public Ventana(int level)
    {
        this.level = level;
        addKeyListener(new KeyboardInterface());
        setFocusable(true);
        setDoubleBuffered(true);
        
        initializeMartianGroup1();
        initializeMartianGroup2();
        initializeMartianGroup3();
        initializeMartianGroup4();
        
        background = new Background();
        spacecraft = new Spacecraft();
        
        timer = new Timer(5, this);
        timer.start();
    }
    
    public void initializeMartianGroup1()
    {
        martianGroup1 = new ArrayList<MartianGroup1>();
        if (martianGroup1.isEmpty() == false)
        {
            martianGroup1.clear();
        }
        
        for (int position=0; position < 5; position++)
        {
            martianGroup1.add(position, new MartianGroup1(position));
        } 
    }
    
    public void paint (Graphics g)
    {
        super.paint(g);
        
        g.drawImage(background.getImage(), background.getX(), background.getY(), this);
        
        switch(counter)
        {
            case 0: paintGroup1(g); break;
            case 1: paintGroup2(g); break;
            case 2: paintGroup3(g); break;
            case 3: paintGroup4(g); break;
            default: break;
        }
        
        paintShots(g);
        
        g.drawImage(spacecraft.getImage(), spacecraft.getX(), spacecraft.getY(), this);
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }
    
    public void actionPerformed(ActionEvent e)
    {
        switch(counter)
        {
            case 0: moveGroup1(); checkCollisionsGroup1(); break;
            case 1: moveGroup2(); checkCollisionsGroup2(); break;
            case 2: moveGroup3(); checkCollisionsGroup3(); break;
            case 3: moveGroup4(); checkCollisionsGroup4(); break;
            default: break;
        }
        
        ArrayList<Shot> activeShots = spacecraft.getShots();
        
        for (int i = 0; i < activeShots.size(); i++)
        {
            Shot shot = activeShots.get(i);
            if (shot.esVisible())
            {
                shot.move();
            }
            else { activeShots.remove(i); }
        }
        
        spacecraft.move();
        repaint();
    }
    
    public void paintGroup1(Graphics g)
    {
        MartianGroup1 martianInUse;
        Iterator<MartianGroup1> martianIterator  = martianGroup1.iterator();
        while(martianIterator.hasNext())
        {
            martianInUse = martianIterator.next();
            if (martianInUse.getVisible() == true)
            {
                g.drawImage(martianInUse.getImage(), martianInUse.getX(), martianInUse.getY(), this);
            }
        }
    }
    
    public void paintShots(Graphics g)
    {
        ArrayList<Shot> activeShots = spacecraft.getShots();
        
        for (int i = 0; i < activeShots.size(); i++)
        {
            Shot shot = activeShots.get(i);
            if (shot.esVisible())
            {
                g.drawImage(shot.getImage(), shot.getX(), shot.getY(), this);
            }
        }
    }
    
    public void moveGroup1() 
    {
        int martianCounter = 0;
        boolean visible = false;
        MartianGroup1 martianInUse;
        Iterator<MartianGroup1> martianIterator  = martianGroup1.iterator();
        while(martianIterator.hasNext())
        {
            martianInUse = martianIterator.next();
            martianInUse.move(martianCounter);
            if (martianIterator.hasNext() == false && martianInUse.getX() == (-60))
            {
                int position = 0;
                Iterator<MartianGroup1> martianIterator2  = martianGroup1.iterator();
                while(martianIterator2.hasNext())
                {
                    martianIterator2.next().restart(position);
                    position++;
                }
                counter++;
            }
            if (martianInUse.getVisible()) { visible = true; }
            martianCounter++;
        }
        if (!visible) { counter++; }
    }
    
    public void checkCollisionsGroup1()
    {
        Rectangle r3 = spacecraft.getBounds();
        
        for (int i = 0; i < martianGroup1.size(); i++)
        {
            Rectangle r2 = martianGroup1.get(i).getBounds();
            
            if (r3.intersects(r2))
            {
                spacecraft.setVisible(false);
            }
        }
        
        ArrayList<Shot> activeShots = spacecraft.getShots();
        
        for (int j = 0; j < activeShots.size(); j++)
        {
            Shot shot = activeShots.get(j);
            
            Rectangle r1 = shot.getBounds();
            for (int i = 0; i < martianGroup1.size(); i++)
            {
                if(martianGroup1.get(i).getVisible())
                {
                    Rectangle r2 = martianGroup1.get(i).getBounds();
                    
                    if (r1.intersects(r2))
                    {
                        shot.setVisible(false);
                        martianGroup1.get(i).setVisible(false);
                    }
                }
            }
        }
    }
    
    public class KeyboardInterface extends KeyAdapter
    {        
        public void keyPressed(KeyEvent e)
        {
            spacecraft.keyPressed(e);
        }
        
        public void keyReleased(KeyEvent e)
        {
            spacecraft.keyReleased(e);
        }
    }
}

Etiquetas: funcionar, programa
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:22.