关于new一个线程的错误 本帖最后由 tmhk123 于 2010-06-02 01:57:02 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 顺便问下 论坛里怎么在java代码中把错误改为红字 你定义的PaintThread类是TankClient中的非静态内部类,即它是与某个TankClient对象相关的,而不是与TankClient类相关的。而main方法是static方法,static方法的结果与调用它的对象无关,即TankClient a = new TankClient(); TankClient b = new TankClient();a.main(...) 和b.main(....)的执行结果应该相同,所以不能再static方法中创建与调用该方法的对象相关的实例,而你原先代码中生成却是a.PaintThread b.PaintThread对象,所以编译器报错import java.awt.*;import java.awt.event.*;public class TankClient extends Frame { int x=50; int y=50; public void paint(Graphics g) { Color c = g.getColor(); g.setColor(Color.RED); g.fillOval(x, y, 30, 30); g.setColor(c); y +=5; } public void lauchFrame() { this.setLocation(400, 300); this.setSize(800, 600); this.setTitle("TankWar"); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); this.setResizable(false); this.setBackground(Color.GREEN); setVisible(true); Thread t1 =new Thread(new PaintThread());/////// t1.start();///////////// } public static void main(String[] args) { TankClient tc = new TankClient(); tc.lauchFrame(); //Thread t1 =new Thread(new PaintThread()); //t1.start(); } class PaintThread implements Runnable{ public void run() { while(true){ repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } } 改下main方法public static void main(String[] args) { TankClient tc = new TankClient(); tc.lauchFrame(); Thread t1 = new Thread(tc.new PaintThread()); t1.start(); } 2、3楼的方法都不错,不过还是建议用2楼的,毕竟内部类是隶属于TankClient的,还是在TankClient里面用 eclipse下 windowbuilder如何切换到控件界面 请问JAVA下有没有采用 OBEX发送文件的代码? 学JAVA,应该选些什么书? String类的参数传递方式的问题和探讨!(高分) 谁知道怎么判断打印结束? 遇到的一个有趣的题目 谁有JBuilder6注册机呀?? 请各位帮忙看一下这个有关MediaTracker类的代码! ERP都是开发的吗? weblogic什么时候需要重新启动 可以用java在linux下调用DLL文件吗 请问这样做线程安全吗?
a.main(...) 和b.main(....)的执行结果应该相同,所以不能再static方法中创建与调用该方法的对象相关的实例,而你原先代码中生成却是a.PaintThread b.PaintThread对象,所以编译器报错
import java.awt.*;
import java.awt.event.*;public class TankClient extends Frame {
int x=50;
int y=50;
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.fillOval(x, y, 30, 30);
g.setColor(c);
y +=5;
} public void lauchFrame() {
this.setLocation(400, 300);
this.setSize(800, 600);
this.setTitle("TankWar");
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setResizable(false);
this.setBackground(Color.GREEN);
setVisible(true);
Thread t1 =new Thread(new PaintThread());///////
t1.start();///////////// } public static void main(String[] args) {
TankClient tc = new TankClient();
tc.lauchFrame();
//Thread t1 =new Thread(new PaintThread());
//t1.start(); }
class PaintThread implements Runnable{
public void run() {
while(true){
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
TankClient tc = new TankClient();
tc.lauchFrame();
Thread t1 = new Thread(tc.new PaintThread());
t1.start();
}