代码:
import java.awt.Point;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Demo8 extends JFrame{
//本实例使用多线程同时控制多个JLable组件的移动,其中每个JLabel组件都设置了
//图标对象为气球图片,当气球移除窗体时,会重新出现在窗体底部继续移动
//注意:添加背景的要在添加小图片之后。
private ImageIcon[] img = new ImageIcon[3];
private static JLabel[] imgLabel = new JLabel[3];
public Demo8(){
setTitle("实现气球的移动");
setBounds(100, 100, 550, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
ImageIcon background = new ImageIcon(getClass().getResource("background.jpg"));
JLabel label = new JLabel(background);
label.setSize(background.getIconWidth(), background.getIconHeight());
label.setLocation(0, 0);
img[0] = new ImageIcon(getClass().getResource("balloon1.png"));
img[1] = new ImageIcon(getClass().getResource("balloon2.png"));
img[2] = new ImageIcon(getClass().getResource("balloon3.png"));
imgLabel[0] = new JLabel(img[0]);
imgLabel[0].setSize(img[0].getIconWidth(), img[0].getIconHeight());
//imgLabel[0].setLocation(20, 300);
getContentPane().add(imgLabel[0]);
imgLabel[1] = new JLabel(img[1]);
imgLabel[1].setSize(img[1].getIconWidth(),img[1].getIconHeight());
//imgLabel[1].setBounds(250, 250, 80, 181);
getContentPane().add(imgLabel[1]);
imgLabel[2] = new JLabel(img[2]);
imgLabel[2].setSize(img[2].getIconWidth(),img[2].getIconHeight());
//imgLabel[2].setBounds(400, 450, 100, 147);
getContentPane().add(imgLabel[2]);
getContentPane().add(label);//为什么了?一定添加在他们的后边
}
public static class thread_1 extends JFrame implements Runnable{
@Override
public void run() {
while(true){
for(int i=300;i>0;i-=15){
imgLabel[0].setLocation(20, i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static class thread_2 extends JFrame implements Runnable{
@Override
public void run() {
while(true){
for(int i=250;i>0;i-=15){
imgLabel[1].setLocation(250, i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static class thread_3 extends JFrame implements Runnable{
@Override
public void run() {
while(true){
for(int i=450;i>0;i-=15){
imgLabel[2].setLocation(400, i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Demo8 demo = new Demo8();
demo.setVisible(true);
Thread thread_1 = new Thread(new thread_1());
thread_1.start();
Thread thread_2 = new Thread(new thread_2());
thread_2.start();
Thread thread_3 = new Thread(new thread_3());
thread_3.start();
}
}