首先,我想说对不起,如果我的问题听起来不是很具体,我对编程不是很了解,请原谅我。
这段代码的问题是我希望它随机移动方块(虽然知道它只是反复打招呼)但是 run() 没有激活。
代码:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.net.*;
public class Square extends JApplet {
int X = 10;
int Y = 10;
public void init() {
FlowLayout flow = new FlowLayout();
setLayout(flow);
}
public void paint(Graphics screen) {
// Paint lines
Graphics2D g2 = (Graphics2D) screen;
g2.draw(new Line2D.Double(X, Y, (X + 50), Y));
g2.draw(new Line2D.Double(X, Y, X, (Y + 50)));
g2.draw(new Line2D.Double(X, (Y + 50), (X + 50), (Y + 50)));
g2.draw(new Line2D.Double((X + 50), (Y + 50), (X + 50), Y));
}
public void run() {
System.out.println("Hi2");
while (true) {
System.out.println("Hi");
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Square");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
JApplet applet = new Square();
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(550,100));
f.setVisible(true);
}
}
(我知道我导入了一些我可能不需要的东西,我从另一个代码中复制了一些)