Metals corrode when it reacts with air and moisture. Presence of both air and water are necessary for corrosion. When the substance is painted , it cut off the contact between metal and air, thus metal is not able to react with air and moisture. So it does not corrode when painted.