有大佬看到的话希望帮忙解决一下注释的那三行,还有就是有什么更好的意见可以提出来,感谢!!
代码:
import javax.swing.*;
import java.awt.*;
public class imgUp extends JFrame {
//定义一个背景图片
ImageIcon background = new ImageIcon("img\\Blue.jpg");
JLabel l = new JLabel(background);//将背景图片放入l标签
//定义一个p面板
JPanel p = new JPanel();
//定义三个气球图片
ImageIcon img1 = new ImageIcon("D:\\java\\MyThread\\img\\1.png");
ImageIcon img2 = new ImageIcon("D:\\java\\MyThread\\img\\2.png");
ImageIcon img3 = new ImageIcon("D:\\java\\MyThread\\img\\3.png");
//同理将图片放入三个标签内
JLabel lImg1 = new JLabel(img1);
JLabel lImg2 = new JLabel(img2);
JLabel lImg3 = new JLabel(img3);
//因为三个图片大小相同,所以用一个代替便于线程run方法的使用
int imgW = img2.getIconWidth();
int imgH = img2.getIconHeight();
public void init(JFrame frame,int width,int height){
frame.setLocationRelativeTo(null);//窗口居中
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口即退出程序
frame.setSize(width, height);//设置窗口大小
Container contentPane = frame.getContentPane();
contentPane.setLayout(null);//空布局
background.setImage(background.getImage().getScaledInstance(width,height,Image.SCALE_DEFAULT));//使图片按窗口大小缩放
//下面也可以
// Image img = background.getImage();
// img = img.getScaledInstance(width,height,Image.SCALE_DEFAULT);
// background.setImage(img);
p.setSize(background.getIconWidth(),background.getIconHeight());//设置面板大小与背景图片大小相同
p.add(l);//将有背景图片的标签l添加到p面板
contentPane.add(lImg1);
contentPane.add(lImg2);
contentPane.add(lImg3);
contentPane.add(p);//将p面板添加到容器中
frame.setVisible(true);
//定义一个Runnable接口对象
Runnable r = new Runnable() {
int runY = 100;//初始的纵坐标
@Override
public void run() {
while (true){
try {
if (runY>-imgH){
switch (Thread.currentThread().getName()){
case "img1":lImg1.setBounds(20,runY--,imgW, imgH);break;
case "img2":lImg2.setBounds(100,runY--,imgW, imgH);break;
case "img3":lImg3.setBounds(180,runY--,imgW, imgH);break;
}
}else{
runY = height-imgH;
}
Thread.sleep(100);//休息0.1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
//定义三个线程对象
Thread t1 = new Thread(r,"img1");
Thread t2 = new Thread(r,"img2");
Thread t3 = new Thread(r,"img3");
//启动线程
t1.start();
t2.start();
t3.start();
}
public static void main(String[] args) {
imgUp i = new imgUp();
//调用init方法
i.init(new JFrame(),500,300);
}
}
效果图:

?
|