Java - Ayuda con KeyListener

 
Vista:

Ayuda con KeyListener

Publicado por javajunior (13 intervenciones) el 04/02/2011 16:45:28
Saludos, otra vez pidiendo ayuda. Mi situación es la siguiente:

He creado un juego que simula una batalla al estilo Final Fantasy. Todo funciona. También creé una aplicación menú para que administre los resultados, el estado de tu personaje. Ambas están por separado, el Jframe del menú es una aplicación, el Jframe de la batalla es otra.

Ambas las he integrado, cosa que la batalla ahora jala datos de la aplicación del menú que accede a base de datos y todo lo demás. Todo eso corre perfecto, el detalle está es que por sí sola, en la batalla, el KEYLISTENER funciona bien, con la tecla ENTER ataco al enemigo y todo muy bien. Pero cuando la integro, se carga el JFrame sobre el JFrame de menú (osea, tengo dos ventanas en total) y el keyListener no funciona, es decir no puedo apretar enter, pero la lógica del juego continua, el enemigo sí ataca
¿a qué podría deberse esto?

Agradecería su respuesta. El código de la clase que ejecuta la batalla es así:

public class LaunchBattle extends JFrame
{
Graphics2D wDisplay;

BufferedImage bSurface;
Graphics2D bOps;

spBackground sBack[];
spChara sParty[];
spChara sEnemy[];

boolean kbKeys[];
boolean sbActive;

int stBack;
int stMusic;

static final int WND_WIDTH = 640;
static final int WND_HEIGHT = 480;

static MascotaService mascotaService = new MascotaService();
static EnemyBean enemigo = null;
static BattleScenario battleinterface = new BattleScenario();
static MascotaPersonalBean mascota = null;
static boolean whoWin = false;
public LaunchBattle(spBackground sb[], spChara sp[], spChara se[])
{

sBack = sb;
sParty = sp;
sEnemy = se;

kbKeys = new boolean [256];
sbActive = true;

stBack = 0;
stMusic = 0;

addWindowListener(new WindowAdapter()
{

public void windowClosing(WindowEvent w)
{

System.exit(0);

}

});

this.addKeyListener(new KeyAdapter()
{

public void keyPressed(KeyEvent k)
{
System.out.println("WEEEE");
kbKeys[k.getKeyCode()] = true;

}

public void keyReleased(KeyEvent k)
{

kbKeys[k.getKeyCode()] = false;

}

});

setSize(WND_WIDTH, WND_HEIGHT);
setTitle("RPG PIDSW");

setVisible(true);

wDisplay = (Graphics2D) getContentPane().getGraphics();
wDisplay.scale(2.0f, 2.0f);

bSurface = new BufferedImage((WND_WIDTH / 2), (WND_HEIGHT) / 2, BufferedImage.TYPE_INT_RGB);
bOps = bSurface.createGraphics();

start();

}

public void start()
{
while (sbActive)
{

if ((System.currentTimeMillis() - ct) >= 20)
{

//Actualizo el cambio de mi tiempo
for (int r = 0; r < sParty.length; r = r + 1)
{

if (sParty[r].isUncon == false)
{

if (sParty[r].ct < sParty[r].mt)
sParty[r].ct = sParty[r].ct + sParty[r].bspd;

if (sParty[r].ct >= sParty[r].mt)
if (actMenu == null)
actMenu = new spActionMenu(sParty[r], sParty[r].sAction);

}

}

for (int r = 0; r < sEnemy.length; r = r + 1)
{

if (sEnemy[r].ct < sEnemy[r].mt)
sEnemy[r].ct = sEnemy[r].ct + sEnemy[r].bspd;

// Revisar antes de enviar!!!!
if (sEnemy[r].ct >= sEnemy[r].mt)
{

int s, t;

do {

t = (int) (Math.random() * sEnemy[r].sAction.length);

} while (sEnemy[r].sAction[t] == null);

do {

s = (int) (Math.random() * sParty.length);

} while (sParty[s].chp <= 0);

sEnemy[r].sAction[t].exec(sEnemy[r], sParty[s]);
sEnemy[r].ct = 0;

}

}

// Update menus on keypress.
if (actMenu != null)
{

// Update action menu.
if (tarMenu == null)
{

if (kbKeys[KeyEvent.VK_DOWN])
{

while (actMenu.cSel < (actMenu.sAction.length - 1))
{

actMenu.cSel = actMenu.cSel + 1;

if (actMenu.sAction[actMenu.cSel] != null)
break;

}

kbKeys[KeyEvent.VK_DOWN] = false;

}

if (kbKeys[KeyEvent.VK_UP])
{

while (actMenu.cSel > 0)
{

actMenu.cSel = actMenu.cSel - 1;

if (actMenu.sAction[actMenu.cSel] != null)
break;

}

kbKeys[KeyEvent.VK_UP] = false;

}

if (kbKeys[KeyEvent.VK_ENTER])
{

tarMenu = new spTargetMenu(sParty, sEnemy, actMenu.sAction[actMenu.cSel].selType);
kbKeys[KeyEvent.VK_ENTER] = false;

}

}

// Update target menu.
if (tarMenu != null)
{

if (kbKeys[KeyEvent.VK_LEFT])
{

// To do, avoid dead characters.

if (tarMenu.cSel > 0)
tarMenu.cSel = tarMenu.cSel - 1;
else
tarMenu.cSel = tarMenu.sSelect.length - 1;

kbKeys[KeyEvent.VK_LEFT] = false;

}

if (kbKeys[KeyEvent.VK_RIGHT])
{

if (tarMenu.cSel < tarMenu.sSelect.length - 1)
tarMenu.cSel = tarMenu.cSel + 1;
else
tarMenu.cSel = 0;

kbKeys[KeyEvent.VK_RIGHT] = false;

}

if (kbKeys[KeyEvent.VK_ENTER])
{

tarMenu.sSelect[tarMenu.cSel].sAction[actMenu.cSel].exec(actMenu.sSrc, tarMenu.sSelect[tarMenu.cSel]);
actMenu.sSrc.ct = 0;

actMenu = null;
tarMenu = null;

kbKeys[KeyEvent.VK_ENTER] = false;

}

}

}

// Verificar los estados para ver si alguna mascota ha perdido toda su vida
int pdTotal = 0;
for (int r = 0; r < sParty.length; r = r + 1)
{

if (sParty[r].isUncon == false)
{

if (sParty[r].chp <= 0)
{

sParty[r].chp = 0;
sParty[r].ct = 0;
sParty[r].isUncon = true;

pdTotal++;

}

}

}

if (pdTotal == sParty.length) {
whoWin = true;
sbActive = false;
}


// Validar la condición de mi enemigo
int edTotal = 0;
for (int r = 0; r < sEnemy.length; r++)
{

if (sEnemy[r].isUncon == false)
{

if (sEnemy[r].chp <= 0)
{

sEnemy[r].chp = 0;
sEnemy[r].ct = 0;
sEnemy[r].isUncon = true;

edTotal++;

}

}

}

if (edTotal == sEnemy.length) {
whoWin = false;
sbActive = false; }

// Refresh the screen.
refresh(actMenu, tarMenu);

// Update the time needed before refresh.
ct = System.currentTimeMillis();
ft_c = ft_c + 1;

}

if ((System.currentTimeMillis() - ft) >= 1000)
{

this.setTitle("RPG PIDSW - " + String.valueOf(ft_c));
ft = System.currentTimeMillis();
ft_c = 0;

}

}

this.setVisible(false);

}

public void refresh(spActionMenu am, spTargetMenu tm)
{

// Clear the buffer.
bOps.setColor(Color.BLACK);
bOps.fillRect(0, 0, bSurface.getWidth(), bSurface.getHeight());

// Set the font and color.
bOps.setFont(new Font("System", Font.PLAIN, 10));
bOps.setColor(Color.WHITE);

// Draw the background.
bOps.drawImage(sBack[stBack].getSurface(), 0, 0, null);

// Draw the party sprites.
for (int r = 0; r < sParty.length; r = r + 1)
{

sParty[r].isClear();
bOps.drawImage(sParty[r].getSurface(), (230 + (r * 10)), (60 + (r * 20)), null);

if (tm != null)
{

if (tm.sSelect[tm.cSel] == sParty[r])
bOps.fillRect((230 + (r * 10)), (60 + (r * 20)), 10, 10);

}

}

for (int r = 0; r < sEnemy.length; r = r + 1)
{

if (sEnemy[r].isUncon == false)
{

sEnemy[r].isClear();
bOps.drawImage(sEnemy[r].getSurface(), (30 + (r * 10)), (60 + (r * 20)), null);

if (tm != null)
{

if (tm.sSelect[tm.cSel] == sEnemy[r])
bOps.fillRect((30 + (r * 10)), (60 + (r * 20)), 10, 10);

}

}

}


if (tm != null)
{

bOps.setColor(Color.ORANGE);
bOps.fillRect(0, 0, bSurface.getWidth(), 15);
bOps.setColor(Color.RED);
bOps.drawString(tm.sSelect[tm.cSel].nName, 3, 10);

}




}

public static void iniciar()
{
spBackground sb[];
spChara sp[];
spChara se[];

AuxiliarEventos ev[];

sb = new spBackground[1];
sp = new spChara[1];
se = new spChara[1];

sb[0] = new spBackground("res/forest1.jpg");

ev = new AuxiliarEventos[4];
ev[0] = new spAttack("Fight");
//ev[3] = new spEvent("Items", spEvent.ST_PARTY);

for (int r = 0; r < sp.length; r = r + 1)
sp[r] = new spChara(mascota, mascota.getObjMascotaInicial().getNombre(), ev, 1);

ev = new AuxiliarEventos[4];
ev[0] = new spAttack("Fight");
ev[1] = new AuxiliarEventos("Taunt", AuxiliarEventos.ST_ENEMY);

for (int r = 0; r < se.length; r = r + 1)
se[r] = new spChara(enemigo, enemigo.getNombre() + String.valueOf(r), ev, 3);

LaunchBattle db = new LaunchBattle(sb, sp, se);

}

}
Lo invoco así : LaunchBattle.iniciar();
gracias de antemano
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Ayuda con KeyListener

Publicado por Carlos (1 intervención) el 12/02/2011 02:30:03
HAHAHAH nadie responde weon no se q vaos a ahcer =(
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Ayuda con KeyListener

Publicado por Ludo (4 intervenciones) el 12/02/2011 21:56:20
Creo que el problema ocurre cuando creas el JFrame sobre el JFrame antiguo, el primero pasa "adelante" y el KeyListener del antiguo deja de recibir datos del teclado, ya que estarías parado sobre el nuevo JFrame... ¿se entiende? puede que sea eso porque me ha pasado. Saludos.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Ayuda con KeyListener

Publicado por Demorado (1 intervención) el 21/07/2014 07:38:08
Supongo q ya encontraste solucion. Pues si usas 2 JFrame y no escucha el teclado tienes q cambiar d foco con setFocusable(true); para q escuche al nuevo JFrame q tienes.. por otra parte haber si me ayudas a mi.
digamos q tienes 2 telcas A, B. Si presionas solo A hace algo, si presionas solo B hace otra cosa, pero si presionas A seguidos por B tiene q hacer el evento q hace solo A, luego el d solo B mas un extra q es el d combinar. Si presionaras en distinto orden B luego A tiene q hacer el de B luego de A y al final otro evento q es la combinación.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar