因此,我正在阅读'Thinking in java‘的书,我偶然看到了ColorBox程序,随意改变盒子的颜色。但是,我注意到在运行这段代码时出现了一个问题,就好像没有run()方法一样。
我在下面突出显示了"/HERE/“)
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.*;
import java.util.*;
import static sun.misc.PostVMInitHook.run;
class CBox extends JPanel implements Runnable {
private int pause;
private static Random rand = new Random();
private Color color = new Color(0);
public void paintComponent(Graphics g) {
g.setColor(color);
Dimension s = getSize();
g.fillRect(0, 0, s.width, s.height);
}
public CBox(int pause) { this.pause = pause; }
public void run() {
try {
while(!Thread.interrupted()) {
color = new Color(rand.nextInt(0xFFFFFF));
repaint(); // Asynchronously request a paint()
TimeUnit.MILLISECONDS.sleep(pause);
}
} catch(InterruptedException e) {
// Acceptable way to exit
}
}
}
public class ColorBoxes extends JFrame {
private int grid = 12;
private int pause = 50;
private static ExecutorService exec =
Executors.newCachedThreadPool();
public void setUp() {
setLayout(new GridLayout(grid, grid));
for(int i = 0; i < grid * grid; i++) {
CBox cb = new CBox(pause);
add(cb);
exec.execute(cb);
}
}
public static void main(String[] args) {
ColorBoxes boxes = new ColorBoxes();
if(args.length > 0)
boxes.grid = new Integer(args[0]);
if(args.length > 1)
boxes.pause = new Integer(args[1]);
boxes.setUp();
/**HERE**/ run(boxes, 500,400);
}
}我没有改变任何东西,这是书中的确切密码。他们希望改进以前的版本,包括JApplet,并且有这样的方法:
public static void run(JApplet applet, int width, int height) {
....
}发布于 2018-05-16 10:42:51
魔鬼在细节里
import static sun.misc.PostVMInitHook.run;这将允许您按给定的方式调用run()。
但是,这并不是很好,因为它使用的是sun.*包,而且您不需要这样做就可以运行程序。可能是过去遗留下来的。
更常用的风格应该是
SwingUtilities.invokeLater(() -> {
boxes.setSize(500, 400);
boxes.setVisible(true);
});https://stackoverflow.com/questions/50368679
复制相似问题