我怎样才能在JPanel中绘制一些不会重新绘制的东西,我正在做一个交通模拟程序,我想要画一次道路,因为它不会改变。 谢谢

有帮助吗?

解决方案

我不确定你真的希望自己的道路永远不会被重新绘制 - 重新调整事件时(例如)在调整窗口大小时,或者在另一个窗口阻挡它时它会变得可见。如果你的小组从不重新粉刷,那么它看起来很奇怪。

据我所知,Swing只会针对这些情况触发适当的绘制事件,因此您应该按照通常的方法使用合适的覆盖子继承JPanel:

public class RoadPanel extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // your drawing code here
    }
}

如果您将道路缓存为图像或其他图形格式(以便多次计算显示数据),一旦绘制一次,这可能会为后续绘画节省一些时间。

其他提示

据我所知,不,除非有透明叠加技巧。

我看到(并且做过)的大多数图形应用程序只是在每次重绘时重新绘制整个面板。现在,您可以在图形缓冲区中执行一次,然后通过将图形缓冲区复制到JPanel,立即快速绘制整个背景。它应该比调用所有图形基元更快地绘制道路。

或者,一些2D游戏的方式,或许可以画一次并更新移动部件,比如精灵:它需要擦除精灵使用的旧地方(恢复那里的背景)并重新绘制精灵。新的地方。因此,您仍然可以在图形缓冲区中获得道路的副本,但不是每次都重新绘制它,而是仅更新一些小部件。可以稍快一些。

每次面板遮挡时都需要重新绘制组件(即框架最小化/另一个窗口放在顶部)。因此,只绘制一次东西不会像你想要的那样工作。要更有效地绘制不变化的零件,可以将它们绘制一次到“缓冲”图像,然后每次需要重新绘制面板或组件时绘制此缓冲区。

// Field that stores the image so it is always accessible
private Image roadImage = null;
// ...
// ...
// Override paintComponent Method
public void paintComponent(Graphics g){

  if (roadImage == null) {
      // Create the road image if it doesn't exist
      roadImage = createImage(width, height);
      // draw the roads to the image
      Graphics roadG = roadImage.getGraphics();
      // Use roadG like you would any other graphics
      // object to draw the roads to an image
  } else {
      // If the buffer image exists, you just need to draw it.
      // Draw the road buffer image
      g.drawImage(roadImage, 0, 0, null);
  }
  // Draw everything else ...
  // g.draw...
}

我所做的是设置一个布尔值,以确定是否需要重绘某个部分。然后,在 paintComponent()方法中,我可以检查值并重绘某些东西。

protected void paintComponent(Graphics g){
    super.paintComponent(g);
    if (drawRoad) {
        drawRoadMethod(g);
    }
    drawTheRest(g);
}

有点像。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top