when clicking a JButton animation starts but keys stops working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pankajs
    New Member
    • Mar 2008
    • 36

    when clicking a JButton animation starts but keys stops working

    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
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    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

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      @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)

      Comment

      • pankajs
        New Member
        • Mar 2008
        • 36

        #4
        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???? ?

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          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

          Comment

          • pankajs
            New Member
            • Mar 2008
            • 36

            #6
            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.I mageIO;
            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","Sa ve2" };
            JButton res,game,load,e xit,save,cred;
            JScrollPane scrollpane;
            public mainwin(Buffere dImage image)
            {
            this.image=imag e;
            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("Credit s");
            exit = new JButton("Exit") ;

            JList list = new JList(categorie s);
            scrollpane = new JScrollPane(lis t);
            event action = new event();
            keyevent kaction = new keyevent();
            add(ngame);
            addKeyListener( kaction);
            ngame.addAction Listener(action );
            exit.addActionL istener(action) ;
            save.addActionL istener(action) ;
            load.addActionL istener(action) ;
            //game.addActionL istener(action) ;
            add(res);
            //add(game);
            add(load);
            add(save);
            add(cred);
            add(exit);


            }

            protected void paintComponent( Graphics g)
            {
            super.paintComp onent(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(im age, x, y, this);
            // Draw text centered over image.
            //Font font = g2.getFont().de riveFont(66f);
            Font font = new Font("Serif",Fo nt.BOLD+Font.IT ALIC,80);
            g2.setFont(font );
            FontRenderConte xt frc = g2.getFontRende rContext();
            float width = (float)font.get StringBounds(te xt, frc).getWidth() ;
            LineMetrics lm = font.getLineMet rics(text, frc);
            float sx = (w - width)/2;
            float sy = (h + lm.getHeight())/2 - lm.getDescent() +180;
            g2.setPaint(Col or.red);
            g2.drawString(t ext, 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.s howConfirmDialo g(null, "Do you want to save your game");
            if(x==0)
            {
            JOptionPane.sho wInputDialog(nu ll,"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.sho wInputDialog(nu ll,"Enter the file name");
            }
            else if(e.getSource( )==load)
            {
            JFrame f1 = new JFrame();
            f1.setDefaultCl oseOperation(JF rame.HIDE_ON_CL OSE);
            f1.setSize(300, 400);
            f1.getContentPa ne().add(scroll pane, BorderLayout.CE NTER);
            f1.setVisible(t rue);
            }

            }
            }
            public class keyevent extends JFrame implements KeyListener
            {
            public void keyPressed(KeyE vent e)
            {
            JOptionPane.sho wMessageDialog( null,"Enter the file name");
            int key = e.getKeyCode();
            if(key == KeyEvent.VK_LEF T)
            {


            JOptionPane.sho wMessageDialog( null,"dfasdme") ;
            }
            else if(key == 27)
            System.exit(0);
            }
            public void keyReleased(Key Event e)
            {}
            public void keyTyped(KeyEve nt e)
            {}
            }

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

            String path ="mains.jpg" ;
            BufferedImage image = ImageIO.read(ne w 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(t rue);
            }
            }


            import java.awt.Canvas ;
            import java.awt.Color;
            import java.awt.Dimens ion;
            import java.awt.Graphi cs2D;
            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.HashM ap;
            import java.awt.event. *;
            import javax.imageio.I mageIO;
            import javax.swing.JFr ame;
            import javax.swing.JPa nel;

            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,explo sion=false, Missile=false,i nvad=false, missile=false, Missile1=false, missile1=false, Monster1=true,M onster2=true, Monster3=true,M onster4=true,Pl ayer=true;
            public BufferStrategy strategy;
            public HashMap sprites;
            public Rectangle Ms,Ms1,In1,M1,M 2,M3,M4,P;
            public int posX,pX,pY,posY ,vX,t=0,posX1,p osY1,mX,mY,m1X, m1Y,MX,MY,M1X,M 1Y,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=p X=40; mY=m1Y=MY=M1Y=p Y=350;
            P = new Rectangle(pX,pY ,32,32);
            Ms = new Rectangle(mX,mY ,32,32);
            Ms1 = new Rectangle(m1X,m 1Y,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,i nY,25,25);
            addKeyListener( this);
            JFrame ventana = new JFrame("Invader s");
            JPanel panel = (JPanel)ventana .getContentPane ();
            setBounds(0,0,W IDTH,HEIGHT);
            panel.setPrefer redSize(new Dimension(WIDTH ,HEIGHT));
            panel.setLayout (null);
            panel.add(this) ;
            ventana.setBoun ds(0,0,WIDTH,HE IGHT);
            ventana.setVisi ble(true);
            ventana.addWind owListener( new WindowAdapter() {
            public void windowClosing(W indowEvent e) {
            System.exit(0);
            }
            });
            ventana.setResi zable(false);
            createBufferStr ategy(2);
            strategy = getBufferStrate gy();
            requestFocus();
            }

            public BufferedImage loadImage(Strin g nombre) {
            URL url=null;
            try {
            url = getClass().getC lassLoader().ge tResource(nombr e);
            return ImageIO.read(ur l);
            } catch (Exception e) {
            System.out.prin tln("No image found " + nombre +" de "+url);
            System.out.prin tln("location error : "+e.getClass(). getName()+" "+e.getMessage( ));
            System.exit(0);
            return null;
            }
            }

            public BufferedImage getSprite(Strin g nombre) {
            BufferedImage img = (BufferedImage) sprites.get(nom bre);
            if (img == null) {
            img = loadImage(nombr e);
            sprites.put(nom bre,img);
            }
            return img;
            }

            public void paintWorld() {
            Graphics2D g = (Graphics2D)str ategy.getDrawGr aphics();
            g.setPaint(new TexturePaint(ge tSprite("oceano .gif"), new Rectangle(t,0,g etSprite("ocean o.gif").getWidt h(),getSprite(" oceano.gif").ge tHeight())));
            g.fillRect(0,0, getWidth(),getH eight());

            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(get Sprite("bicho.g if"), posX1, posY1,this);
            if(Monster2)
            g.drawImage(get Sprite("bicho.g if"), posX1-30, posY1-30,this);
            if(Monster3)
            g.drawImage(get Sprite("bicho.g if"), posX1-60, posY1-60,this);
            if(Monster4)
            g.drawImage(get Sprite("bicho.g if"), posX1-90, posY1-90,this);



            for(int k=0;k<5;k++)
            {
            In1 =new Rectangle(inX,i nY,25,25);
            if(invad)
            g.drawImage(get Sprite("invader .jpg"),inX,inY, this);
            inX+=30;
            inY+=30;
            }
            if(Player)
            g.drawImage(get Sprite("nave.gi f"),pX,pY,this) ;
            if(explosion)
            {
            long extime=System.c urrentTimeMilli s();
            g.drawImage(get Sprite("explosi on.gif"),pX,pY, this);
            long exusTime=System .currentTimeMil lis()-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(get Sprite("misil.g if"),mX,mY,this ); mX+=10;
            Ms = new Rectangle(mX,mY ,32,32);
            }
            if(missile1)
            {
            g.drawImage(get Sprite("rocket. gif"),m1X,m1Y,t his); m1X+=10;
            Ms1 = new Rectangle(m1X,m 1Y,60,15);
            }

            if (usedTime > 0)
            g.drawString(St ring.valueOf(10 00/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=Monste r2=Monster3=Mon ster4=false;
            }
            INX-=vX;
            inX=INX;
            inY=INY;

            if(INX<0)
            {
            invad=false;
            INX=WIDTH;
            Monster1=Monste r2=Monster3=Mon ster4=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.intersect s(M1))
            {
            Monster1=false; missile=false;
            }
            if(Ms1.intersec ts(M1))
            {
            Monster1=false; missile1=false;
            }
            if(Ms.intersect s(M2))
            {
            Monster2=false; missile=false;
            }
            if(Ms1.intersec ts(M2))
            {
            Monster2=false; missile1=false;
            }
            if(Ms.intersect s(M3))
            {
            Monster3=false; missile=false;
            }
            if(Ms1.intersec ts(M3))
            {
            Monster1=false; missile1=false;
            }
            if(Ms.intersect s(M4))
            {
            Monster4=false; missile=false;
            }
            if(Ms1.intersec ts(M4))
            {
            Monster4=false; missile1=false;
            }

            }

            public void keyPressed(KeyE vent e)
            {
            int key = e.getKeyCode();
            if(Player)
            {
            if(key== KeyEvent.VK_LEF T)
            { pX-=10; MX=M1X=pX;}
            else if(key== KeyEvent.VK_RIG HT)
            { pX+=10; MX=M1X=pX;}
            else if(key== KeyEvent.VK_UP)
            { pY-=10; MY=M1Y=pY;}
            else if(key== KeyEvent.VK_DOW N)
            { 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=missi le1=true;}
            P = new Rectangle(pX,pY ,32,32);
            }
            }
            public void keyReleased(Key Event e)
            {}
            public void keyTyped(KeyEve nt e)
            {}
            public void game() {
            usedTime=1000;
            while (loop) {
            long startTime = System.currentT imeMillis();
            updateWorld();
            paintWorld();
            t--;
            usedTime = System.currentT imeMillis()-startTime;
            try {
            Thread.sleep(SP EED);
            } catch (InterruptedExc eption e) {}
            }
            }

            /*public static void main(String[] args) {
            Invaders1 inv = new Invaders1();
            inv.game();
            }*/
            }

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              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

              Comment

              Working...