为什么我的按扭不能动?Java

来源:百度知道 编辑:UC知道 时间:2024/09/28 08:03:24
import javax.swing.*;

public class Seven extends Thread{

JFrame form=new JFrame("窗体");
JButton bu=new JButton("按钮");

public static void main(String[] args){
new Seven().fun();
}
public void fun(){
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setBounds(200, 200, 700, 700);
form.add(bu);
form.setLayout(null);
bu.setBounds(0, 0, 100, 30);
Thread th=new Seven();
form.setVisible(true);
th.start();
}

public void run(){
int a=10,b=10;
while(true){
bu.setBounds(a, b, 100, 30);
a+=10;
b+=10;
try {
sleep(200);
} catch (InterruptedException e) {System.out.println("aaa");}
if(a>=300){
a=10;
b=10;
}
}
}

}
要是把run里的代码放到fun里面就可以动了.这是那里有问题>?

如果想要启动一个thread的话,必须显示的调用它的start函数,而你在main函数的调用fun函数只是一个简单的调用,并不是启动了一个新的thread(线程)来做这件事情的。你把main函数写成下面这个样子:
public static void main(String[] args){
Seven s = new Seven();
s.fun();
s.start();
}
或者按照下面这个样子写(推荐):
public class Seven extends Thread{

JFrame form=new JFrame("窗体");
JButton bu=new JButton("按钮");

public Seven() {
super();
fun();
}

public static void main(String[] args){
new Seven().start();
}
public void fun(){
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setBounds(200, 200, 700, 700);
form.add(bu);
form.setLayout(null);
bu.setBounds(0, 0, 100, 30);
Thread th=new Seven();
form.setVisible(true);
th.start();
}

public void run(){
int a=10,b=10;
while(true){
bu.setBounds(a, b, 100, 30);
a+=10;
b+=10;
try {
sleep(200);