![](/img/trans.png)
[英]Two lines of my System.out.println code do not work and I cannot figure out why
[英]Why my graphics code don't run unless there is a System.out.println in the code block?
我有这个方法paint()接收Graphics2D参数。 发生的奇怪事情是,除非存在System.out.println(我在下面的块中注释掉),否则画布不会绘制任何内容。
public class Map{
public void paint(Graphics2D g){
//fill background to black
g.setColor(Color.black);
g.fillRect(0, 0, TILE_SIZE*WIDTH, TILE_SIZE*HEIGHT);
//draw the tiles and buildings
for(int i=0;i<WIDTH;i++){
for(int j=0;j<HEIGHT;j++){
if(map[j][i] == CLEAR){
//System.out.println("");
g.setColor(Color.gray);
g.fillRect(i*TILE_SIZE, j*TILE_SIZE, TILE_SIZE, TILE_SIZE);
g.setColor(Color.red);
g.drawRect(i*TILE_SIZE, j*TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
}
}
}
在这里,我使用BufferStrategy在Canvas上绘制并将其添加到Frame。 这个方法在Map类中,它将从BufferStrategy的getDrawGraphics()方法传递一个Graphics2D(我希望很多人都熟悉这些东西来理解我在做什么)。
public class MapTest extends Canvas{
private Map map;
public MapTest(){
Frame frame = new Frame("MAP");
frame.add(this);
frame.setVisible(true);
createBufferStrategy(2);
strategy = getBufferStrategy();
//draw the map
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
//g.translate(100, 100);
map.paint(g);
g.dispose();
strategy.show();
}
}
此代码来自Canvas类。 正如您所看到的,paint()方法与Canvas类(我将其命名为GameTest)分开。 因此,如果我注释掉println语句,那么画布中不会显示图形,否则会正确显示。 任何人都可以帮助我???
您应该使用SwingUtilities切换到Event Dispatch Thread(EDT),见下文。 这几乎是与AWT和Swing类的所有交互所必需的。
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new MapTest();
}
}
请注意,这使用了一个swing助手库,对于AWT应该没用,但更好的是开始使用Swing。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.