Jupiter's Trojans are asteroids that follow essentially the same orbit as Jupiter, but lead or trail the planet by an angular distance of approximately 60 degrees (co-orbital motion). They are hypothesized to be planetesimals that formed near Jupiter and were captured onto their current orbits while Jupiter was growing, possibly with the help of gas drag and/or collisions. This idea, however, cannot explain some basic properties of the Trojan population, in particular its broad orbital inclination distribution, which ranges up to approximately 40 degrees (ref. 8). Here we show that the Trojans could have formed in more distant regions and been subsequently captured into co-orbital motion with Jupiter during the time when the giant planets migrated by removing neighbouring planetesimals. The capture was possible during a short period of time, just after Jupiter and Saturn crossed their mutual 1:2 resonance, when the dynamics of the Trojan region were completely chaotic. Our simulations of this process satisfactorily reproduce the orbital distribution of the Trojans and their total mass.