Connecting Tech Pros Worldwide Forums | Help | Site Map

when clicking a JButton animation starts but keys stops working

Member
 
Join Date: Mar 2008
Posts: 36
#1: Mar 17 '08
Hello freinds! I m making a game but I m facing a problem that when I click New Game button(defined by me) animation starts. But in the animation keys are not working even the Close button at the right top of the window stops working......

So plz! can anyone help me in solving this problem..........

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Mar 17 '08

re: when clicking a JButton animation starts but keys stops working


Quote:

Originally Posted by pankajs

Hello freinds! I m making a game but I m facing a problem that when I click New Game button(defined by me) animation starts. But in the animation keys are not working even the Close button at the right top of the window stops working......

So plz! can anyone help me in solving this problem..........

Without reading your code my guess is that you're doing all your work in the AWT
Event dispatching thread so that it can't do anything else. In the worst case
you're using Thread.sleep() for your animation too. Carefully design your threads
for the animation logic, the event listening as well as the drawing of the animation.

kind regards,

Jos
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#3: Mar 17 '08

re: when clicking a JButton animation starts but keys stops working


@OP: I just found your double post on this subject; I deleted the thread. Don't
double post your single problem but stay in one thread for it; otherwise you
confuse people and people might even try to help you while it's not needed
anymore.

kind regards,

Jos (mod)
Member
 
Join Date: Mar 2008
Posts: 36
#4: Mar 17 '08

re: when clicking a JButton animation starts but keys stops working


do u mean that Thread.sleep is not suitable for gaming when including actionListener ???
Can u suggest me any different way to animate & adding keyListener?????
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#5: Mar 17 '08

re: when clicking a JButton animation starts but keys stops working


Quote:

Originally Posted by pankajs

do u mean that Thread.sleep is not suitable for gaming when including actionListener ???
Can u suggest me any different way to animate & adding keyListener?????

Well, the Thread.sleep() method is fine but not in the AWT event dispatch thread.
You effectively kill the thread for some time and it won't be able to respond to
any user gesture; also reread my previous reply and try to show us some sample
code that may show what and how you're doing things now.

kind regards,

Jos
Member
 
Join Date: Mar 2008
Posts: 36
#6: Mar 18 '08

re: when clicking a JButton animation starts but keys stops working


here is the full code what I have done till today
It starts autmatically but when I click New Game, no key works
to obtain mainwindow press 'P'
import java.awt.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;

public class mainwin extends JPanel
{
BufferedImage image;
JButton ngame;
Invaders1 inv;
String text = "COMBAT MISSION";
String categories[] = { "Save1","Save2" };
JButton res,game,load,exit,save,cred;
JScrollPane scrollpane;
public mainwin(BufferedImage image)
{
this.image=image;
this.inv = inv;
ngame = new JButton("New Game");
res = new JButton("Resume");
//game = new JButton("New Game");
load = new JButton("Load");
save = new JButton("Save");
cred = new JButton("Credits");
exit = new JButton("Exit");

JList list = new JList(categories);
scrollpane = new JScrollPane(list);
event action = new event();
keyevent kaction = new keyevent();
add(ngame);
addKeyListener(kaction);
ngame.addActionListener(action);
exit.addActionListener(action);
save.addActionListener(action);
load.addActionListener(action);
//game.addActionListener(action);
add(res);
//add(game);
add(load);
add(save);
add(cred);
add(exit);


}

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
// Draw image, centered.
int x = (w - image.getWidth())/2;
int y = (h - image.getHeight())/2;
g2.drawImage(image, x, y, this);
// Draw text centered over image.
//Font font = g2.getFont().deriveFont(66f);
Font font = new Font("Serif",Font.BOLD+Font.ITALIC,80);
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
float width = (float)font.getStringBounds(text, frc).getWidth();
LineMetrics lm = font.getLineMetrics(text, frc);
float sx = (w - width)/2;
float sy = (h + lm.getHeight())/2 - lm.getDescent()+180;
g2.setPaint(Color.red);
g2.drawString(text, sx, sy);
}

public class event extends JFrame implements ActionListener
{


private int x,sav=0;
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ngame)
inv.game();
if(e.getSource()==exit)
{
if(sav==0)
{

x=JOptionPane.showConfirmDialog(null, "Do you want to save your game");
if(x==0)
{
JOptionPane.showInputDialog(null,"Enter the file name");
System.exit(0);
}
else if(x==1)
System.exit(0);
}
else
System.exit(0);
}
else if(e.getSource()==save)
{
sav++;
JOptionPane.showInputDialog(null,"Enter the file name");
}
else if(e.getSource()==load)
{
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
f1.setSize(300,400);
f1.getContentPane().add(scrollpane, BorderLayout.CENTER);
f1.setVisible(true);
}

}
}
public class keyevent extends JFrame implements KeyListener
{
public void keyPressed(KeyEvent e)
{
JOptionPane.showMessageDialog(null,"Enter the file name");
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT)
{


JOptionPane.showMessageDialog(null,"dfasdme");
}
else if(key == 27)
System.exit(0);
}
public void keyReleased(KeyEvent e)
{}
public void keyTyped(KeyEvent e)
{}
}

public static void main(String[] args) throws IOException
{

String path ="mains.jpg";
BufferedImage image = ImageIO.read(new File(path));
JFrame j1 = new JFrame();
mainwin test = new mainwin(image);
Invaders1 inv = new Invaders1();
inv.game();
j1.add(test);
j1.setSize(800,600);
j1.setVisible(true);
}
}


import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Invaders1 extends Canvas implements KeyListener{
public static final int WIDTH = 800;
public static final int HEIGHT =600;
public static final int SPEED = 10;
public boolean loop=true,explosion=false, Missile=false,invad=false, missile=false, Missile1=false, missile1=false,Monster1=true,Monster2=true, Monster3=true,Monster4=true,Player=true;
public BufferStrategy strategy;
public HashMap sprites;
public Rectangle Ms,Ms1,In1,M1,M2,M3,M4,P;
public int posX,pX,pY,posY,vX,t=0,posX1,posY1,mX,mY,m1X,m1Y,M X,MY,M1X,M1Y,inX,inY,INX,INY;
public long usedTime;

public Invaders1() {
sprites = new HashMap();
INX=inX=posX = posX1=WIDTH;
INY=inY=posY = posY1=HEIGHT/2-150;
vX = 2;
mX=m1X=MX=M1X=pX=40; mY=m1Y=MY=M1Y=pY=350;
P = new Rectangle(pX,pY,32,32);
Ms = new Rectangle(mX,mY,32,32);
Ms1 = new Rectangle(m1X,m1Y,60,15);
M1= new Rectangle(posX,posX,32,32);
M2= new Rectangle(posX-30,posY-30,32,32);
M3= new Rectangle(posX-60,posY-60,32,32);
M4= new Rectangle(posX-90,posY-90,32,32);
In1= new Rectangle(inX,inY,25,25);
addKeyListener(this);
JFrame ventana = new JFrame("Invaders");
JPanel panel = (JPanel)ventana.getContentPane();
setBounds(0,0,WIDTH,HEIGHT);
panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
panel.setLayout(null);
panel.add(this);
ventana.setBounds(0,0,WIDTH,HEIGHT);
ventana.setVisible(true);
ventana.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
ventana.setResizable(false);
createBufferStrategy(2);
strategy = getBufferStrategy();
requestFocus();
}

public BufferedImage loadImage(String nombre) {
URL url=null;
try {
url = getClass().getClassLoader().getResource(nombre);
return ImageIO.read(url);
} catch (Exception e) {
System.out.println("No image found " + nombre +" de "+url);
System.out.println("location error : "+e.getClass().getName()+" "+e.getMessage());
System.exit(0);
return null;
}
}

public BufferedImage getSprite(String nombre) {
BufferedImage img = (BufferedImage)sprites.get(nombre);
if (img == null) {
img = loadImage(nombre);
sprites.put(nombre,img);
}
return img;
}

public void paintWorld() {
Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
g.setPaint(new TexturePaint(getSprite("oceano.gif"), new Rectangle(t,0,getSprite("oceano.gif").getWidth(),g etSprite("oceano.gif").getHeight())));
g.fillRect(0,0,getWidth(),getHeight());

M1= new Rectangle(posX1,posY1,32,32);
M2= new Rectangle(posX1-30,posY1-30,32,32);
M3= new Rectangle(posX1-60,posY1-60,32,32);
M4= new Rectangle(posX1-90,posY1-90,32,32);
if(Monster1)
g.drawImage(getSprite("bicho.gif"), posX1, posY1,this);
if(Monster2)
g.drawImage(getSprite("bicho.gif"), posX1-30, posY1-30,this);
if(Monster3)
g.drawImage(getSprite("bicho.gif"), posX1-60, posY1-60,this);
if(Monster4)
g.drawImage(getSprite("bicho.gif"), posX1-90, posY1-90,this);



for(int k=0;k<5;k++)
{
In1 =new Rectangle(inX,inY,25,25);
if(invad)
g.drawImage(getSprite("invader.jpg"),inX,inY,this) ;
inX+=30;
inY+=30;
}
if(Player)
g.drawImage(getSprite("nave.gif"),pX,pY,this);
if(explosion)
{
long extime=System.currentTimeMillis();
g.drawImage(getSprite("explosion.gif"),pX,pY,this) ;
long exusTime=System.currentTimeMillis()-extime;
if(exusTime>.25)
explosion=false;
}
if(Missile1)
{m1X=M1X; m1Y=M1Y; Missile1=false;}
if(Missile)
{mX=MX; mY=MY; Missile=false;}
if(missile)
{
g.drawImage(getSprite("misil.gif"),mX,mY,this); mX+=10;
Ms = new Rectangle(mX,mY,32,32);
}
if(missile1)
{
g.drawImage(getSprite("rocket.gif"),m1X,m1Y,this); m1X+=10;
Ms1 = new Rectangle(m1X,m1Y,60,15);
}

if (usedTime > 0)
g.drawString(String.valueOf(1000/usedTime)+" fps",0,HEIGHT-50);
else
g.drawString("--- fps",0,HEIGHT-50);
strategy.show();
}



public void updateWorld() {
posX -= vX;
posX1=posX;
posY1=posY;
if(posX<0)
{
posX=WIDTH;
invad=true;
Monster1=Monster2=Monster3=Monster4=false;
}
INX-=vX;
inX=INX;
inY=INY;

if(INX<0)
{
invad=false;
INX=WIDTH;
Monster1=Monster2=Monster3=Monster4=true;
}
if(P.intersects(M1))
{
Player=false;
explosion=true;
}
if(P.intersects(M2))
{
Player=false;
explosion=true;
}
if(P.intersects(M3))
{
Player=false;
explosion=true;
}
if(P.intersects(M4))
{
Player=false;
explosion=true;
}
if(Ms.intersects(M1))
{
Monster1=false; missile=false;
}
if(Ms1.intersects(M1))
{
Monster1=false; missile1=false;
}
if(Ms.intersects(M2))
{
Monster2=false; missile=false;
}
if(Ms1.intersects(M2))
{
Monster2=false; missile1=false;
}
if(Ms.intersects(M3))
{
Monster3=false; missile=false;
}
if(Ms1.intersects(M3))
{
Monster1=false; missile1=false;
}
if(Ms.intersects(M4))
{
Monster4=false; missile=false;
}
if(Ms1.intersects(M4))
{
Monster4=false; missile1=false;
}

}

public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(Player)
{
if(key== KeyEvent.VK_LEFT)
{ pX-=10; MX=M1X=pX;}
else if(key== KeyEvent.VK_RIGHT)
{ pX+=10; MX=M1X=pX;}
else if(key== KeyEvent.VK_UP)
{ pY-=10; MY=M1Y=pY;}
else if(key== KeyEvent.VK_DOWN)
{ pY+=10; MY=M1Y=pY;}

else if(key==27)
System.exit(0);
else if(key== KeyEvent.VK_P)
{
if(loop==true)
loop=false;
else
{
loop=true;
game();
}
}
else if(key ==32)
{ Missile=missile=true;}
else if(key==17)
{Missile1=missile1=true;}
P = new Rectangle(pX,pY,32,32);
}
}
public void keyReleased(KeyEvent e)
{}
public void keyTyped(KeyEvent e)
{}
public void game() {
usedTime=1000;
while (loop) {
long startTime = System.currentTimeMillis();
updateWorld();
paintWorld();
t--;
usedTime = System.currentTimeMillis()-startTime;
try {
Thread.sleep(SPEED);
} catch (InterruptedException e) {}
}
}

/*public static void main(String[] args) {
Invaders1 inv = new Invaders1();
inv.game();
}*/
}
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#7: Mar 18 '08

re: when clicking a JButton animation starts but keys stops working


Quote:

Originally Posted by pankajs

here is the full code what I have done till today
It starts autmatically but when I click New Game, no key works
to obtain mainwindow press 'P'

That was just too much code (and without the [ code ] tags). All I did was
browse a bit through it but I don't see a separate thread for the game logic and
a separate thread for handling the events. I also find the actual drawing logic
a bit smelly, i.e. you don't use the paintComponent() method (I might have
missed it). Are you able to produce a short piece of code that shows the same
bug? This was just too much code.

kind regards,

Jos
Reply