Thursday 9 February 2012

How to close child windows when closing parent window in javascript?

In many instances we want to close all child windows when main parent window is closed. This can be easily achieved using javascript.

To achieve this we need to do three thing

1) Create an array. This array is required for storing references of all child windows.


var childwindows = new Array();

2) Open child window using window.open and then store references of child window into an array

function openPopup(){
 try{
  var d = new Date();
  var win = window.open("Test.html",'test'+d.getMilliseconds(),'width=200,height=100')
  childwindows[childwindows.length] = win;
  win.focus();
 }catch(e){
  alert(e);
 }
}

3) Finally close all child windows on window.onunload event.

window.onunload = function closeChildWin(){
 for(var i=0; i<childwindows.length; i++){
  try{
     childwindows[i].close()
  }catch(e){
   alert(e);
  }
 }
}



To test this you can copy and paste following code into the file and save it as a Test.html. Let me know if it has helped you.

<html>
 <body>
        <input type="submit" onclick="openPopup()" value="Open new Window">
 </body>
</html>

<script>

var childwindows = new Array();

function openPopup(){
 try{
  var d = new Date();
  var win = window.open("Test.html",'test'+d.getMilliseconds(),'width=200,height=100')
  childwindows[childwindows.length] = win;
  win.focus();
 }catch(e){
  alert(e);
 }
}

window.onunload = function closeChildWin(){
 for(var i=0; i<childwindows.length; i++){
  try{
     childwindows[i].close()
  }catch(e){
   alert(e);
  }
 }
}

</script>

Friday 3 February 2012

JBox2D with JavaFX 2.0 Tutorial: Attaching an image to body

In Write your first JBox2D with JavaFX 2 program posts we have seen how to create a ball and its GUI representation using JavaFX Circle shape. We can also use images for GUI representation. Following code snippet shows how to attach an image to the body.

import javafx.scene.Parent;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;

/**
 *
 * @author dilip
 */
public class Ball extends Parent{

    
    //X and Y position of the ball in JBox2D world
    private float posX;
    private float posY;
    
    //Ball radius in pixels
    private int radius;
    
    public Ball(float posX, float posY, int radius){
        this.posX = posX;
        this.posY = posY;
        this.radius = radius;
        create();
    }

    
    private void create(){
        
        /**
         * Set ball position on JavaFX scene. We need to convert JBox2D coordinates 
         * to JavaFX coordinates which are in pixels.
         */
        this.setLayoutX(Utils.toPixelPosX(posX)); 
        this.setLayoutY(Utils.toPixelPosY(posY));
        
        //Create an JBox2D body defination for ball.
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DYNAMIC;;
        bd.position.set(posX, posY);
        
        CircleShape cs = new CircleShape();
        cs.m_radius = radius * 0.1f;  //We need to convert radius to JBox2D equivalent
        
        // Create a fixture for ball
        FixtureDef fd = new FixtureDef();
        fd.shape = cs;
        fd.density = 0.5f;
        fd.friction = 0.3f;        
        fd.restitution = 0.5f;

        /**
        * Virtual invisible JBox2D body of ball. Bodies have velocity and position. 
        * Forces, torques, and impulses can be applied to these bodies.
        */
        Body body = Utils.world.createBody(bd);
        body.createFixture(fd);
        this.setUserData(body);

        //Attach an image.
        ImageView iv = new ImageView();
        iv.setSmooth(true);
        iv.setImage(new Image(Ball.class.getResourceAsStream("images/ball.png")));
        getChildren().add(iv);
    }
}

Friday 20 January 2012

How to calculate an age in Java?

Can we calculate an age in java without worrying about number of leap years between birth date and current date? Is there simple way to calculate it? …. The answer is yes. When we calculate somebody’s age manually, we do not think about number of leap year or number of days in each year. Same logic can be applies for calculating age programmatically.

Following is a code snippet for calculating the age. Please leave comment if it has helped you. Also please let me know if you feel this can be further optimized or this can be achieved by more simpler way...

  int years = 0;
  int months = 0;
  int days = 0;
  
  //create calendar object for birth day
  Calendar birthDay = Calendar.getInstance();
  birthDay.set(Calendar.YEAR, 2005);
  birthDay.set(Calendar.MONTH, Calendar.SEPTEMBER);
  birthDay.set(Calendar.DATE, 29);
  
  //create calendar object for current day
  long currentTime = System.currentTimeMillis();
  Calendar currentDay = Calendar.getInstance();
  currentDay.setTimeInMillis(currentTime);

  //Get difference between years
  years = currentDay.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);

  
  int currMonth = currentDay.get(Calendar.MONTH)+1;
  int birthMonth = birthDay.get(Calendar.MONTH)+1;
  
  //Get difference between months
  months = currMonth - birthMonth;
  
  //if month difference is in negative then reduce years by one and calculate the number of months. 
  if(months < 0)
  {
   years--;
   months = 12 - birthMonth + currMonth;
   
   if(currentDay.get(Calendar.DATE)<birthDay.get(Calendar.DATE))
    months--;
   
  }else if(months == 0 && currentDay.get(Calendar.DATE) < birthDay.get(Calendar.DATE)){
   years--;
   months = 11;
  }
  
  
  //Calculate the days
  if(currentDay.get(Calendar.DATE)>birthDay.get(Calendar.DATE))
   days = currentDay.get(Calendar.DATE) -  birthDay.get(Calendar.DATE);
  else if(currentDay.get(Calendar.DATE)<birthDay.get(Calendar.DATE)){
   int today = currentDay.get(Calendar.DAY_OF_MONTH); 
   currentDay.add(Calendar.MONTH, -1);
   days = currentDay.getActualMaximum(Calendar.DAY_OF_MONTH)-birthDay.get(Calendar.DAY_OF_MONTH)+today;
  }else{
   days=0;
   
   if(months == 12){
    years++;
    months = 0;
   }
  }
  
  System.out.println("The age is : "+years+" years, "+months+" months and "+days+" days" );


Tuesday 10 January 2012

JBox2D with JavaFX tutorial: Applying Force and Impulse on body

Many times there will be situation when in JBox2D world we want to move bodies manually. So how do we do it? In real world we apply force to move anything. It holds good in JBox2D world too. To move bodies in JBox2D world we have to apply Force or Impulse.

There is a difference between force and Impulse. Force act gradually on bodies’ velocity. Imagine in real world if we wants to move one big box from one location to other then we will start pushing it. It means we will gradually apply force on that box; as a result box will start moving. Force in JBox2D world also works in similar fashion.

Following is a code snippet for applying force on body.
Body body = (Body)ball.getUserData();
Vec2 force  = new Vec2(0, 150.0f);
Vec2 point = body.getWorldPoint(body.getWorldCenter());
body.applyForce(force ,point);

Impulse act instantaneously, in a fraction of time step. Impulse is like we strike snooker ball with a cue or move objects with the help of explosives. Applying impulse is similar to applying force. We need to use applyLinearImpulse() function in place of applyForce()

Following sample code snippet is for applying the impulse.
Body body = (Body)ball.getUserData();
Vec2 force  = new Vec2(0, 50.0f);
Vec2 point = body.getWorldPoint(body.getWorldCenter());
body. applyLinearImpulse (force ,point);

The applyForce() and applyLinearImpulse() function takes two parameters force and point. Force parameter defines a direction and magnitude of the force. And second parameter defines on which point of the body force should be applied. In above snippet, we are applying force/impulse on center of the body.

<<JBox2D With JavaFX : Write your first JBox2D with JavaFX 2 program