import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FishFrame extends JFrame implements Runnable {
JPanel panel;
JLabel label;
public FishFrame() {
super();
getContentPane().setLayout(null);
setBounds(100, 100, 340, 190);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(null);
panel.setBounds(0, 0, 337, 159);
getContentPane().add(panel);
URL url = getClass().getResource("1.png");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setBounds(271, 47, 66, 60);
panel.add(label);
Thread thread = new Thread();
thread.start();
}
public static void main(String[] args) {
FishFrame frame = new FishFrame();
frame.setVisible(true);
}
@Override
public void run() {
while (true) {
int lx = label.getX() - 1;
if (label.getX() - 1 > panel.getX()) {
label.setLocation(lx, getY());
} else {
label.setBounds(271, 47, 66, 60);
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
看下编译器报了什么错误。
资源有没有读到。
panel.setLayout(null);//panel都没定义
run方法也不会执行。runnable不是线程,要实现线程
FishFrame frame = new FishFrame();
frame.setVisible(true);
new Thread(frame).start();//加上这句才实现线程
panel.setLayout(null);//panel都没定义
run方法也不会执行。runnable不是线程,要实现线程
FishFrame frame = new FishFrame();
frame.setVisible(true);
new Thread(frame).start();//加上这句才实现线程
没有编写主函数main()
下面是改好的代码,2个大问题:
1. 对象没有初始化,panel和label都没有;
2. Thread对象实例化不对,或者说使用的不对,没有传入参数。你的FishFrame实现了Runnable接口,那么线程要用FishFrame来构建,加个this就可以了。
其他的代码中注释了,自己看下吧。
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FishFrame extends JFrame implements Runnable {
//需要初始化对象再使用
JPanel panel = new JPanel();
JLabel label = new JLabel("label");
public FishFrame() {
super();
getContentPane().setLayout(null);
setBounds(100, 100, 340, 190);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(null);
panel.setBounds(0, 0, 337, 159);
getContentPane().add(panel);
//下面的url不知道你的工程是怎么配置的,我注释了。
//URL url = getClass().getResource("1.png");
ImageIcon imageIcon = new ImageIcon("./01.png");
label.setIcon(imageIcon);
label.setBounds(271, 47, 66, 60);
panel.add(label);
// 原来的线程没有意义,没有具体参数就是一个空线程,加上this才对。
Thread thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
FishFrame frame = new FishFrame();
frame.setVisible(true);
//增加一个关闭处理方法,一般都这么写
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void run() {
while (true) {
int lx = label.getX() - 1;
if (label.getX() - 1 > panel.getX()) {
label.setLocation(lx, getY());
} else {
label.setBounds(271, 47, 66, 60);
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}