Help with KeyDown (space invaders game)

I'm making a space invaders type game for school using Greenfoot (new Java IDE). Whenever I press space, a bullet will fire. However, multiple bullets are being created when I press space once, and when I hold space, a long stream of bullets are being made. I want one bullet to be created when I press space. Tried using KeyPress, but apparently Greenfoot does not recognize java.awt? Thanks in advance.
public class Ship extends Vehicle {
     * Constructor for objects of class Shuttle
    public Bullet B;
    boolean canFire = false;
    public Ship() {
        GreenfootImage ship = new GreenfootImage("spaceship.gif");
        this.setImage(ship);       
    //Create a bullet
    public void fire(){
        B = new Bullet();
        getWorld().addObject(B,getX(),getY()-60);
    public boolean collision(){
        Actor enemy = getOneIntersectingObject(null);
        return (enemy!=null) ? true : false;
    public void act(){
        // move with keys
        if (this.canMove())
             move();      
        if(Greenfoot.isKeyDown("space")){               
                fire();               
        else if(collision()){
            getWorld().removeObject(this);                           
}

Make a Class Variable to use as a flag indicating that a key was pressed... check to see if the flag is set, and if it is not, then fire a bullet and then set the flag. Reset the flag when they keyReleased action fires.
This way only one bullet can be fired for each time a key is pressed, provided your act() is being polled, but if a keyPressed fires act(), but not a keyRelease too, then it will not work. If it does not work, then you'll need to go to a regular KeyListener.
//Your code make these changes
public class Ship extends Vehicle {
      * Constructor for objects of class Shuttle
     public Bullet B;
     boolean canFire = false;
     public Ship() {
         GreenfootImage ship = new GreenfootImage("spaceship.gif");
         this.setImage(ship);       
     //Create a bullet
     public void fire(){
         B = new Bullet();
         getWorld().addObject(B,getX(),getY()-60);
     public boolean collision(){
         Actor enemy = getOneIntersectingObject(null);
         return (enemy!=null) ? true : false;
     public void act(){
         // move with keys
         if (this.canMove())
              move();      
        if(!GreenFoot.isKeyDown("space")) canFire = true; //add this
         if(Greenfoot.isKeyDown("space") and canFire){               
                 fire();              
                 canFire = false; //add this
         else if(collision()){
             getWorld().removeObject(this);                           
}

Similar Messages

  • Need Help with Java Space Invaders Game!

    Hi, im new to these forums so forgive if i dont follow the right way on laying things out. Im trying to create space invaders game but im stuck when im trying to create multiple aliens/ invaders. I have a class called Aliens (which is the invaders), and i can create an instance of an Alien. But when I try to create multiple instances they are not showing up on screen. I am not getting any error message though (which im hoping is a good sign, lol).
    GamePanel is where all the action is and Alien is the alien (invaders) class.
    Here is the code:
    import java.awt.; import javax.swing.; import java.awt.Image; import java.awt.event.KeyListener; import java.awt.event.KeyEvent;
    public class GamePanel extends JComponent implements KeyListener { SpaceInvaders game; static Player player1; Aliens alien1; static public Image spaceship2R; static public Image spaceship2L;
    public GamePanel(SpaceInvaders game)
         this.game = game;
         player1 = new Player(this);
         player1.start();
                   ///// trying to create multiple instances of aliens here
         for(int i=0; i<4; i++)
              alien1 = new Aliens(this);
              alien1.setX(i*100);
              alien1.start();
        this.setFocusable(true);
        this.addKeyListener(this);
    public void paintComponent(Graphics g)
         Image pic1 = player1.getImage();
         Image pic2 = alien1.getImage();
         super.paintComponent(g);
         g.drawImage(pic1, player1.getX(), player1.getY(), 50, 50,this);
         g.drawImage(pic2, alien1.getX(), alien1.getY(), 50, 50,this);
    }//end class
    import java.awt.Image; import java.awt.*;
    class Aliens extends Thread { //variables GamePanel parent; private boolean isRunning; private int xPos = 0, yPos = 0; Thread thread; static char direction = 'r'; Aliens alien; static public Image alien1; static public Image alien2;
    public Aliens(GamePanel parent)
         this.parent = parent;
         isRunning = true;
    public void run()
         while(isRunning)
              Toolkit kit = Toolkit.getDefaultToolkit();
              alien1 = kit.getImage("alien1.gif");
              alien2 = kit.getImage("alien2.gif");
              try
                      thread.sleep(100);
                 catch(InterruptedException e)
                      System.err.println(e);
                 updateAliens();
                 parent.repaint();
    public static Image getImage()
         Image alienImage = alien1;
        switch(direction){
             case('l'):
                  alienImage = alien1;
                  break;
             case('r'):
                  alienImage = alien1;
                  break;
        return alienImage;     
    public void updateAliens()
         if(direction=='r')
              xPos+=20;
              if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                   yPos+=50;
                   xPos-=20;
                   direction='l';
         else
              xPos-=20;
              if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                   yPos+=50;
                   xPos+=20;
                   direction='r';
    public void setDirection(char c){ direction = c; }
    public void setX(int x){ xPos = x; }
    public void setY(int y){ yPos = y; }
    public int getX(){ return xPos; }
    public int getY(){ return yPos; }
    }//end classEdited by: deathwings on Oct 19, 2009 9:47 AM
    Edited by: deathwings on Oct 19, 2009 9:53 AM

    Maybe the array I have created is not being used in the paint method, or Im working with 2 different objects as you put it? Sorry, Im just learning and I appreciate your time and help. Here is my GamePanel Class and my Aliens class:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Image;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferStrategy;
    public class GamePanel extends JComponent implements KeyListener
         SpaceInvaders game;
         static Player player1;
         static Bullets bullet;
         //static public Image spaceship2R;
         //static public Image spaceship2L;
         private BufferStrategy strategy;
         static int alienNum =0;
         static Aliens[] aliens;
         public GamePanel(SpaceInvaders game)
              this.game = game;
              player1 = new Player(this);
              player1.start();
              Aliens[] aliens = new Aliens[10];
              for(int i=0; i<4; i++)
                   aliens[i] = new Aliens(this);
                   aliens.setX(i*100);
                   aliens[i].start();
                   alienNum++;
              initialiseGame();
              this.setFocusable(true);
    this.addKeyListener(this);
         public void paintComponent(Graphics g)
              Image pic1 = player1.getImage();
              Image pic2 = aliens[0].getImage();
              Image bulletPic = bullet.getImage();
              super.paintComponent(g);
              g.drawImage(pic1, player1.getX(), player1.getY(), 50, 50,this);
              for ( int i = 0; i < alienNum; i++ )
                   g.drawImage(pic1, aliens[0].getX(), aliens[0].getY(), 50, 50,this);
              //if (bullet.fired==true){
              //     g.drawImage(bulletPic, bullet.getX(), bullet.getY(), 20, 20,this);
         public void keyPressed(KeyEvent k)
              switch (k.getKeyCode()) {
              case (KeyEvent.VK_KP_DOWN):
              case (KeyEvent.VK_DOWN):
                   player1.setDirection('d');
                   break;
              case (KeyEvent.VK_KP_UP):
              case (KeyEvent.VK_UP):
                   player1.setDirection('u');
              break;
              case (KeyEvent.VK_KP_RIGHT):
              case (KeyEvent.VK_RIGHT):
                   player1.setDirection('r');
              break;
              case (KeyEvent.VK_KP_LEFT):
              case (KeyEvent.VK_LEFT):
                   player1.setDirection('l');
              break;
              case (KeyEvent.VK_SPACE):
                   fireBullet();
              break;
         public void keyTyped(KeyEvent k) {}//empty
         public void keyReleased(KeyEvent k)
              player1.setDirection('n');
         public void initialiseGame()
         public static void checkCollision()
              Rectangle playerRec = new Rectangle(player1.getBoundingBox());
              for(int i=0; i<alienNum; i++)
                   //if(playerRec.intersects(aliens[i].getBoundingBox()))
                        //collisionDetected();
         public static void collisionDetected()
              System.out.println("COLLISION");
         public void fireBullet()
              Bullets bullet = new Bullets(player1.getX(),player1.getY());
              bullet.fired=true;
    }//end GamePanelimport java.awt.Image;
    import java.awt.*;
    class Aliens extends Thread
         //variables
         GamePanel parent;
         private boolean isRunning;
         private int xPos = 0, yPos = 0;
         Thread thread;
         static char direction = 'r';
         Aliens alien;
         static public Image alien1;
         static public Image alien2;
         public Aliens(GamePanel parent)
              this.parent = parent;
              isRunning = true;
         public void run()
              while(isRunning)
                   Toolkit kit = Toolkit.getDefaultToolkit();
                   alien1 = kit.getImage("alien1.gif");
                   //alien2 = kit.getImage("alien2.gif");
                   try
              thread.sleep(100);
         catch(InterruptedException e)
              System.err.println(e);
              updateAliens();
              parent.repaint();
         public static Image getImage()
              Image alienImage = alien1;
         switch(direction){
              case('l'):
                   alienImage = alien1;
                   break;
              case('r'):
                   alienImage = alien1;
                   break;
         return alienImage;     
         public void updateAliens()
              if(direction=='r')
                   xPos+=20;
                   if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                        yPos+=50;
                        xPos-=20;
                        direction='l';
              else
                   xPos-=20;
                   if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                        yPos+=50;
                        xPos+=20;
                        direction='r';
         public Rectangle getBoundingBox()
              return new Rectangle((int)xPos, (int)yPos, 50, 50);
         public void setDirection(char c){ direction = c; }
         public void setX(int x){ xPos = x; }
         public void setY(int y){ yPos = y; }
         public int getX(){ return xPos; }
         public int getY(){ return yPos; }
    }//end class                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How do i remove an Object (aliens/ bullets) from my Space Invaders game??

    Creating Space Invaders game and im getting confused on removing objects from my game. How do you actually remove an object (i.e bullets and aliens).
    I know this isnt the right way to do it, but for the bullets i had an array of the Objects bullets[] and set the x and y coordinates off screen so u cant see then wen they are painted you cant see them, then wen the player fires them, the x and y coordinates change so they come from the players ship till it hits an alien or goes off screen, then i reset the coordinates so they are pasted off screen again. Im relatively new to this so i would appreciate any help. Im going to have to do the same with aliens wen a collision is detected. Is there a way of actually removing an object?
    Here is sum code incase you need to see it:
    public void checkCollision()
              Rectangle playerRec = new Rectangle(player1.getBoundingBox());
              for(int i=0; i<alienRow; i++)
                   for(int j=0; j<alienCol; j++){
                        if(playerRec.intersects(aliens[i][j].getBoundingBox()))
                             collisionDetected();
                        for(int k=0; k<bulletNum; k++){
                             Rectangle bulletRec = new Rectangle(bullets[k].getBoundingBox());
                             if(bulletRec.intersects(aliens[i][j].getBoundingBox()))
                                  removeBullet(bullets[k]);
                                  collisionDetected();
         public static void collisionDetected()
              System.out.println("COLLISION");
    private void removeBullet(Bullets bullet){
              bullet.fired=false;
              bullet.setX(-10);
              bullet.setY(-10);
         }Edited by: deathwings on Nov 25, 2009 8:20 AM

    deathwings wrote:
    I was thinking bout that arraylist angle before, but it makes sense now so i think that will work ok. Thx kevin.Not a problem.
    Taking the List idea one step further, you could have a parent Object/Interface that all of your game objects extend/implement. Let's call it GameObject.
    A GameObject would have a draw(Graphics g) function that you call from your paintComponent( ) method, and for example an act( ) function as well.
    You'd have a single List of GameObjects that you add everything in your game into. Now painting is simply a matter of looping over a single List. And in your game logic loop, you could do a similar thing with the act( ) function: your bullet's act( ) would simply move it forward and check for collisions and going off screen. An alien's act( ) function would move it around and maybe shoot a weapon every so often.
    Just an idea.

  • Firing bullets in space invaders game

    hey guys,
    I am trying to work out the logic and the code required for firing a bullet in a space invaders style game.
    I have a space ship on a stage that moves around freely using the arrow keys and I want to use the space bar to release a bullet.
    So far my thinking is as follows:
    when the space bar is pressed a bullet is released from the players space ship.
    so I need to think about:
    - the speed of the bullet
    - the position of the spaceship when the bullet is fired
    - being able to fire multiple bullets one after the other
    - the bullet should move from the bottom of the screen to the top of the screen
    - the consequence of a bullet hitting a target
    I do not know how many scripts I would need to tackle this? how many behaviours per script and more importantly the code required....
    I am desperate for any help and support you can provide...
    thank you

    thank you for your support
    at this current time it would be a waste of time to understand how things work that did not benefit my game, sure knowledge would give me power but at the moment Id rather concentrate on gaining the appropriate knowledge as per the mechanics of my game and not going off in the opposite direction
    having had a look at your space invaders game and the code and logic you provided it is different to the game I am building because:
    - you use the move for movement and fire whereas I use cursor keys and a space bar
    - you have limited the amount of ammuntion, I have not
    - there are no explosions or changing of cast members on intersection.
    I understand the aim of you posting the guide however I am of the thinking it would be better to follow a tutorial that is in line with what I require rather then learning a particular style and then again having to work out how to amend it again to be used in my game...
    So if anyone can help me understand or provide code as per my initial message , I would be so grateful
    thank you

  • Help with disk space!

    i need some serious help with disk space... so im on itunes today and it says i am running out of disk space and need to delete some files... i deleted every song in my itunes library and it stills gives me this message. i cannot download anything... i dont know what to do to clear up a large amount of disk space... please help. thanks!

    Just some obvious questions first ...did you delete the song from itunes or from a playlist? Did you empty the trash yet ..as deleted files will go to your trash but still take up space until their actually deleted from here.
    Doing a simple 'Get Info' (control + click) on certain files and folders will let you know how much space they are using. This app. also works nice in letting you know where all your space is being used...
    http://grandperspectiv.sourceforge.net/

  • Controlling fire in Space Invaders game

    Hi again,
    still working through the tutorial on Space Invaders in Flash
    MX 2004 (bit out of date, I know).
    I've got the player craft under mouse control. What I don't
    like about the game is that you can fire as rapidly as you wan't,
    though the number of bullets is limited. You can change this limit
    in the variable - I would rather have it though that you can only
    have a set number of bullets in play at a time (at the moment, if
    you go over the limit, the uppermost bullets just disapear).
    Here is the code:
    // when the mouse cliks
    onClipEvent(mouseDown)
    // duplicate the bullet mc
    _root.bullet.duplicateMovieClip("bullet"+bulletNum,bulletNum);
    // set the coords to the mouse clik
    eval("_root.bullet" + bulletNum)._x = this._x;
    eval("_root.bullet" + bulletNum)._y = this._y;
    // increment the bullet number
    bulletNum++;
    // if more than 50 bullets , start again at 0
    if(bulletNum>50)
    bulletNum = 0;
    What code could I use to have it so that you can only have,
    say, 3 bullets in play at once, and you can't fire again until
    they've hit / left the screen?
    regards,
    g

    Hi again,
    thanks for that. Another way would be to use code like the
    following:
    var enableInterval:Number;
    var allowFire:Boolean;
    function tempDisableFire():Void {
    allowFire = false;
    enableInterval = setInterval(enableFire, 500); // 500
    millisecond delay
    function enableFire():Void {
    allowFire = true;
    clearInterval(enableInterval);
    I am unsure though whether to insert this within my existing
    code, or to use this starting from scratch. If it was inside an
    onClipEvent tag (the event being the mouse click), I could then use
    it to control the fire. I'm not sure if I would do this with an "if
    / then" statement.
    Any suggestions on this method? I know it may be asking a bit
    much, but if you could even complete this piece of code that would
    be magic!
    cheers,
    g

  • Need help with a simple basketball game.

    Hi im new here and I need help with making this simple basketball game.
    Im trying to recreate this game from this video. Im not sure if he is using as2 or as3
    Or if anyone could help me make a game like this or direct me to a link on how to do it It would be greatly appreciated.

    If you couldn't tell whether it is AS2 or AS3, it is doubtful you can turn it from AS2 into AS3, at least not until you learn both languages.  There is no tool made that does it for you.

  • Need a bit of help with Jumping in a game

    I making an action game (at least for the sake of this question) and when the user presses the spacebar the character jumps. The problem is, if the character is moving right or left, and jumps while he is moving, he will stop moving in mid-air (if the spacebar is released) and just drop straight down. Example:
    press right arrow key
    player moves right
    press space while pressing arrow key
    player jumps
    let go of spacebar
    player drops straight down (does not continue to move right) //Problem
    It's pretty simple code, actually:
    /* Move player left or right */
    if (pressedRight)
            player.x_pos += player.x_speed;
    else if (pressedLeft)
            player.x_pos -= player.x_speed;
    /* If spacebar is pressed */
    if (pressedSpace && !player.moveUp)
            player.moveUp = true;
            player.y_speed = player.INITIALSPEED;
    /* if you are in "jump mode" */                         
    if (player.moveUp)
            player.y_pos += player.y_speed;
            player.y_speed += .25;
            if (player.y_pos >= TheGround)
                      player.moveUp = false;
                      player.y_speed = 0;
    public boolean keyDown(Event e, int key)
            if(key==Event.LEFT)
                      pressedLeft = true;
            if(key==Event.RIGHT)
                      pressedRight=true;
            if(key==Event.UP)
                      pressedUp=true;
            if(key==Event.DOWN)
                      pressedDown=true;
            if (key ==  ' ')
                      pressedSpace = true;
            repaint();
            return true;
    public boolean keyUp(Event e, int key)
            pressedLeft=false;
            pressedRight = false;
            pressedSpace = false;
            repaint();
            return true;
    }

    Run this code and you'll see what I'm talking about:
    import java.awt.*;
    import java.applet.*;
    public class Testing extends Applet implements Runnable
        Thread runner;
        private Image Buffer;
        private Graphics gBuffer;
        final int theGround = 205;
         boolean pressedLeft, pressedRight, pressedSpace;
         final int width = 10, height = 10;
         final int INITIALSPEED = -5;
         double x_pos = 100;
         double y_pos = 190;
         boolean moveUp = false;
         double y_speed = 3;
         double x_speed = 3;
        //Init is called first, do any initialisation here
        public void init()
            //create graphics buffer, the size of the applet
            Buffer=createImage(size().width,size().height);
            gBuffer=Buffer.getGraphics();
        public void start()
            if (runner == null)
                runner = new Thread (this);
                runner.start();
        public void stop()
            if (runner != null)
                runner.stop();
                runner = null;
        public void run()
            while(true)
                 /* MAIN CODE*/
                //Thread sleeps for 15 milliseconds here
                try {runner.sleep(15);}
                catch (Exception e) { }
                //paint background blue
                gBuffer.setColor(Color.blue);
                gBuffer.fillRect(0,0,size().width,size().height);
                   if (pressedRight)
                        x_pos += 1;
                   else if (pressedLeft)
                        x_pos -= 1;
                   if (pressedSpace && !moveUp)
                        moveUp = true;
                        y_speed = INITIALSPEED;
                   if (moveUp)
                        y_pos += y_speed;
                        y_speed += .15;
                        if (y_pos + height + y_speed >= theGround)
                             moveUp = false;
                             y_speed = 0;
                Draw();
                repaint();
        //is needed to avoid erasing the background by Java
        public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
            g.drawImage (Buffer,0,0, this);
        public boolean keyDown(Event e, int key)
            if(key==Event.LEFT)
                pressedLeft = true;
            if(key==Event.RIGHT)
            pressedRight=true;
            if (key ==  ' ')
                 pressedSpace = true;
            repaint();
            return true;
        public boolean keyUp(Event e, int key)
            pressedLeft=false;
            pressedRight = false;
            pressedSpace = false;
            repaint();
            return true;
        public void Draw()
              gBuffer.setColor(Color.green);
              gBuffer.fillOval((int)x_pos,(int)y_pos,width,height);
              gBuffer.setColor(Color.yellow);
              gBuffer.drawLine(0, 200, 500, 200);
              gBuffer.drawString(("Move right/left, press space, and it will stop and fall straight down! Why?"), 10, 20);
              gBuffer.drawString(("Hold the spacebar down and it will work like it should."), 10, 30);
              gBuffer.drawString(("ALSO, move left or right then *QUICKLY* release and move in the opposite direction."), 10, 50);
                   gBuffer.drawString(("-- You should see it pause for a second. Why is that?"), 10, 60);
    }Sorry for some reason the tabs get messed up when I cut and pate it from JCreator. :P
    PLEASE HELP!
    Thanks in advance.

  • Help with Creating a Jeopardy Game for Classroom Teacher

    Hi,
    I am a middle school teacher and would like to create a Flash Jeopardy game for the teachers at our school to use on our school website.  I would like a game similar to the game on http://www.superteachertools.com/jeopardy/.
    I have been able to successfully create a flash jeopardy game that uses a xml file.  My problem is that I have to have a swf file and an xml file for every game we create.  I want to be able to have one swf file that will load many different Jeopardy games. 
    I am using Flash CS3, Dreamweaver CS3, and MySQL.  The files I have created are here:  http://www.marylynnewilliams.com/MaryLynneWilliams/test/DownloadZIP/JeopardyGames.php
    There is also a zip file:  http://www.marylynnewilliams.com/MaryLynneWilliams/test/DownloadZIP/Jeopardy.zip
    If anyone has time to help me with this it would be greatly appreciated.
    Thank you,
    Mary Lynne

    Hi
    I've had a look at your zip files, and with the best will in the world what your asking for is way beyond what one individual here is willing to invest.
    First of all, this is AS2.0 on the Timeline, most Coders don't do this anymore. It's AS3.0 and Classes now.
    If your able to invest a little time and patient in learning AS3 the rewards are far greater.
    I'm sorry this might not be the answer you where looking for, but it's best you find out now than waiting indefinitely and getting no further with your project.
    Best Regards
    The Feldkircher

  • Need some help with Tic Tac Toe game

    hey. hope u guys can help me out...
    having a problem with my tic tac toe program...
    i have 2 problems.
    1) got the "X" and "O" to appear using a flag(teacher didn't explain)
    using code like this
    if (jb == button[0]){
    if (flag==0)
    button[0].setText("X");
    else
    button[0].setText("O");
    //toggle
    flag = (flag==0)?1:0;
    my problem is how do i get it to stop.(For example button[1] is selected as "X"..how do i stop it from albe to switch to "O")
    2) found this code in javascript online and i want to do what it does in java code
    if(button[0] == " X " && button[1] == " X " && button[2] == " X ")
    alert("You Win!");
    reset();
    how would i do that?
    thanks for the help.

    ok here's my code:
    //TTT.java
    import javax.swing.*;
    import java.awt.*;
    import java .awt.event.*;
    public class TTT extends JFrame
                        implements WindowListener, ActionListener
    private JFrame frFirst;
    private Container cnFirst,cnSecond;
    private     JButton button[]=new JButton[9];
    private JButton btnNewGame,btnExit;
    private FlowLayout southLayout;
    private JPanel southPanel;
    private int flag;
    public TTT()
                   frFirst=new JFrame ("Michael's Tic Tac Toe Game!");
                   cnFirst=frFirst.getContentPane();
                   cnFirst.setLayout (new GridLayout (4,4));
                   cnFirst.setBackground(Color.green);
              for(int i=0;i<button.length;i++)
                        button[i] = new JButton();
                        cnFirst.add(button);
                        flag=0;
              southPanel = new JPanel ();
              btnNewGame = new JButton ("New Game");
              southPanel.add (btnNewGame);
              btnExit = new JButton ("EXIT");
              southPanel.add (btnExit);
              frFirst.add (southPanel,BorderLayout.SOUTH);
              frFirst.setLocation(200, 200);
              frFirst.setSize(400,400);
              frFirst.setResizable(false);
              frFirst.setVisible(true);
              this.frFirst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // listeners
                   frFirst.addWindowListener(this);
                   button[0].addActionListener(this);
                   button[1].addActionListener(this);
                   button[2].addActionListener(this);
                   button[3].addActionListener(this);
                   button[4].addActionListener(this);
                   button[5].addActionListener(this);
                   button[6].addActionListener(this);
                   button[7].addActionListener(this);
                   button[8].addActionListener(this);
                   btnNewGame.addActionListener (this);
                   btnExit.addActionListener (this);
         //define methods of WindowListener
    public void windowOpened(WindowEvent we)
         public void windowClosing(WindowEvent we)
         System.exit(0);
         public void windowClosed(WindowEvent we)
         public void windowIconified(WindowEvent we)
         public void windowDeiconified(WindowEvent we)
         public void windowActivated(WindowEvent we)
         public void windowDeactivated(WindowEvent we)
    public void actionPerformed(ActionEvent ae)
    //making the X and O to appear on JButtons
         Object obj = ae.getSource();
              if (obj instanceof JButton){
                   JButton jb = (JButton)obj;
                   if (jb == button[0])
                        if (flag==0)
                        button[0].setText("X");
                   else
                        button[0].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[1])
                        if (flag==0)
                        button[1].setText("X");
                   else
                        button[1].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[2])
                        if (flag==0)
                        button[2].setText("X");
                   else
                        button[2].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[3])
                        if (flag==0)
                        button[3].setText("X");
                   else
                        button[3].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[4])
                        if (flag==0)
                        button[4].setText("X");
                   else
                        button[4].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[5])
                        if (flag==0)
                        button[5].setText("X");
                   else
                        button[5].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[6])
                        if (flag==0)
                        button[6].setText("X");
                   else
                        button[6].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[7])
                        if (flag==0)
                        button[7].setText("X");
                   else
                        button[7].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[8])
                        if (flag==0)
                        button[8].setText("X");
                   else
                        button[8].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
    //New Game To Reset
              if (ae.getSource () == btnNewGame)
    /*     String text = JOptionPane.showInputDialog(null,"Do You Want To Start A New Game?","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
    String YES;
    if (text == YES)
         JOptionPane.showMessageDialog(null,"Do You","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
         else{
    add code to reset game
         //Exit Button to Exit
         if (ae.getSource () == btnExit)
              JOptionPane.showMessageDialog(null,"Thanks For Playing!","Michael's Tic Tac Toe Game!",JOptionPane.INFORMATION_MESSAGE);
              this.setVisible(false);
         System.exit(0);
              }     //end of if instanceof
    public static void main(String[]args)
         //instantiate GUI
         new TTT();

  • Need Help With Disk Space Issue

    I am trying to free up some disk space on my MacBook Pro. Here is what I have in terms of usage of personal files:
    Music: 24.7 gb
    Pictures: 9.92 gb
    Documents: .379 gb
    Applications: 9.25 gb
    This totals 44.249 gb
    My capacity is listed as 111.47 gb. The problem is that I am showing only 11.96 gb available. I don't understand why there is so much gab between what is listed above and the capacity. I realize the System files, Application Support, etc. use a fair amount, but it still seems like I should have more space. I have run Onyx to clear caches, optimize, etc., and that has helped, but only marginally. Are there large files somewhere I am not aware of? I have an iDisk, but I have iDisk Synching off, so there should not be a copy of it on my computer, unless tere is an old oe lurking somewhere. Thanks a lot for any suggestions.

    I'll give a very plain answer :P
    My Movies folder has a 10 gb size, my Library folder has 5.83 gb, my root Library has 10.89 gb, my System folder has 4.2 gb. I believe there is much more than the basic folders that eats your HDD away.
    I don't know if my folders size are normal, but I do know that adding only your basic folders won't give you the real amount of disk used. In my case I have 20.92 gb of space. I would also look the size of the Downloads folder and the Mail folder (in your home/Library/Mail I have 3.5 GB in one account only!)
    Hope this helps!
    One last thing, not so long ago I saw a post about someone who found a file that was huge, the file was because he let the computer working overnight testing if it ran correctly by letting chess computer vs computer play all night. The game created an enormous file (I believe it was the nbook.db file in username/Library/Application Support/Chess/)
    OR... use what Matt Clifton recommends jajaja... seems like a better idea :P
    Message was edited by: Ehych

  • Can anyone help with clearing space on my Mac Mini, it says the hard drive is full and runs slowly.

    Please help, we got the Mac Mini from a family member so it may have his stuff on it but no longer required, we have only put a smal amount of data on it so don't believe we have over filled it. I backed up to a hard drive all photos etc as I thought it may be them filling it, now I cannot even scan a document to it. Is there any way to Defrag it as you can normally do to a windows system as well as either declutter it or restore the whole thing.
    Best Regards
    Smithy

    The first thing to do with a second-hand computer is to erase the internal drive and install a clean copy of OS X. You — not the previous owner — must do that. How you do it depends on the model, and on whether you already own another Mac. If you're not sure of the model, enter the serial number on this page. Then find the model on this page to see what OS version was originally installed.
    1. You don't own another Mac.
    If the machine shipped with OS X 10.4 or 10.5, you need a boxed and shrink-wrapped retail Snow Leopard (OS X 10.6) installation disc from the Apple Store or a reputable reseller — not from eBay or anything of the kind. If the machine has less than 1 GB of memory, you'll need to add more in order to install 10.6. Preferably, install as much memory as it can take, according to the technical specifications.
    If the machine shipped with OS X 10.6, you need the installation media that came with it: gray installation discs, or a USB flash drive for some MacBook Air models. For early MBA models, you may need a USB optical drive or Remote Disc. You should have received the media from the previous owner, but if you didn't, order replacements from Apple. A retail disc, or the gray discs from another model, will not work.
    To boot from an optical disc or a flash drive, insert it, then reboot and hold down the C key at the startup chime. Release the key when you see the gray Apple logo on the screen.
    If the machine shipped with OS X 10.7 or later, you don't need media. It should boot into Internet Recovery mode when you hold down the key combination option-command-R at the startup chime. Release the keys when you see a spinning globe.
    2. You do own another Mac.
    If you already own another Mac that was upgraded in the App Store to the version of OS X that you want to install, and if the new Mac is compatible with it, then you can install it. Use Recovery Disk Assistant to create a bootable USB device and boot the new Mac from it by holding down the C key at the startup chime. Alternatively, if you have a Time Machine backup of OS X 10.7.3 or later on an external hard drive (not a Time Capsule or other network device), you can boot from that by holding down the option key and selecting it from the row of icons that appears. Note that if your other Mac was never upgraded in the App Store, you can't use this method.
    Once booted in Recovery, launch Disk Utility and select the icon of the internal drive — not any of the volume icons nested beneath it. In the Partition tab, select the default options: a GUID partition table with one data volume in Mac OS Extended (Journaled) format. This operation will permanently remove all existing data on the drive.
    After partitioning, quit Disk Utility and run the OS X Installer. You will need the Apple ID and password that you used to upgrade. When the installation is done, the system will automatically reboot into the Setup Assistant, which will prompt you to transfer the data from another Mac, its backups, or from a Windows computer. If you have any data to transfer, this is usually the best time to do it.
    Then run Software Update and install all available system updates from Apple. To upgrade to a major version of OS X newer than 10.6, get it from the Mac App Store. Note that you can't keep an upgraded version that was installed by the previous owner. He or she can't legally transfer it to you, and without the Apple ID you won't be able to update it in Software Update or reinstall, if that becomes necessary. The same goes for any App Store products that the previous owner installed — you have to repurchase them.
    If the previous owner "accepted" the bundled iLife applications (iPhoto, iMovie, and Garage Band) in the App Store so that he or she could update them, then they're linked to that Apple ID and you won't be able to download them without buying them. Reportedly, Mac App Store Customer Service has sometimes issued redemption codes for these apps to second owners who asked.
    If the previous owner didn't deauthorize the computer in the iTunes Store under his Apple ID, you wont be able to  authorize it immediately under your ID. In that case, you'll either have to wait up to 90 days or contact iTunes Support.

  • Need help with drag and drop game, Urgent!

    Hi I have created a drag and drop game, the drag and drop is
    working alright however once the right word has been placed in the
    box, and moves on to the next question the previous correct answer
    stays where it was placed, how can i get it to snap back to its
    original location? Also when the right word is draged in to the the
    white box i want it to snap into place in that box so it fits in
    there.
    Also if you have any other thoughts and advice on how i can
    improve on this please email me thanx
    Can someone please help, my .fla file can be found here:
    http://www.freshlemon.co.uk/timeline.fla
    http://www.freshlemon.co.uk/timeline.fla.zip
    thanx

    tellTarget is ancient
    I forget what it even used to do??? hahaha
    seriously, just put in the instance name and what you want it
    to do:
    tellTarget("movieclip"){
    play();
    is now just
    movieclip.play();

  • Need help with white spaces/halos when creating PNG

    I'm using Illustrator CS6 on Windows 7. I'm trying to create some pushpins that will go on an online map. I've created the graphic in Illustrator and everything looks nice and sharp. My problem is when I try to convert this .ai file to png. The ai file is set up on 8.5 x 11 artboard with the graphic taking up the whole artboard; the final size of the png needs to be 20x34 pixels at 72 dpi.
    I've tried both Save for Web and Export but no matter what I do, when I open the png in Photoshop, there is a white space between the grey pushpin and the black stroke as well as around the outside of the S. No matter what I've tried, I can't get rid of these unwanted white spaces/halos. Is there a setting I'm missing somewhere? The large image below is how it looks in Illustrator; the small image is the png opened in Photoshop. How can I get the small png to be as crisp as the large ai file? Thanks.

    mc-mark,
    Are you sure the artwork is contained within whole pixels on the Artboard?
    One way to obtain that is to move the artwork so that the Transform panel tells you that the X and Y values of the lower left corner (or centre or something else) are whole pixels/points; another way is to tick Align to Pixel grid  in the Transform panel, but I am afraid that may distort the artwork when used at this stage.

  • Error for 'not enough space' when downloading a video.  I can see that it's music but I'm deleting songs out of my itunes and it's not helping with the space.

    I'm trying to download vide'os to my iPad but I'm getting an error that there is 'not enough space'.  When I look at my space, it's mostly music.  I've deleted out albums from my itunes but it has not freed up any space.  How do I delete these albums?

    Music takes up very little space, movies use a lot of space.
    Settings, music
    Setting, usage
    Both these area will give you info but if the movies are bigger then these areas allow, you may not have enough room even with removing all the music.
    How big are these movies and how many?

Maybe you are looking for

  • Can No Longer See Time Capsule on Windows 7 Laptop

    I installed a time capsule as our home network about a year ago.  The time capsule is hard wired to the FIOS router (FIOS router wireless turned off).  Our computers and digital devices connect to the tme capsule wifi network.  I set up the time caps

  • MSI-6590 USB & Overclocking problem

    Got two things for a real long time messed up on my computer: the first: my keyboard (Logitech Internetkeys USB) won't always work when booting up when it is connected the computer just boots etc but the USB port where it is plugged in (and others to

  • Are there any JDBC Drivers for SQL Server 2000?

    Hello Everyone, Any news on the JDBC drivers for SQL Server 2000? I know it is not certified yet but is there a date when it will be. Which versions of WLS will they work with? Any help is appreciated. Sincerely, --Luis

  • Passing SELECT-OPTIONS to smart forms

    hi ,    how can we pass select options from a program to a smart form. Regards Arun

  • Screen-Exit MM01/MM02/MM03 - Problems when I try to retrieve the data saved

    Hi guys, I created a Screen-Exit in the Accounting View of MM01/MM02/MM03 because I need to insert data into the fields of an Append Structure of the table MBEW, that I created. So, I can insert the data through an User-Exit. I Export to the Memory t