0

我正在尝试制作一个 Java Applet,它允许我在画布中绘制图形数据结构。我将通过单击要创建节点的位置并单击节点来连接它们来做到这一点。问题是我无法让该paint()方法正常运行。我在方法内向图形(和画布上的正方形)添加新节点,mousePressed(MouseEvent e)使用,

Graphics g = this.getGraphics();
g.setColor(Color.blue);
g.fillRect(e.getX(), e.gety(), 40, 40);

一切正常,直到我调整窗口大小,然后所有填充的矩形都消失了。我将paint方法重写为一个空方法,但同样的事情仍然发生。我无法在paint() 中添加fillRect 命令,因为在用户使用鼠标与其交互之前我不知道存在哪些矩形。

如何g.fillRect()在鼠标侦听器方法中使用并使它们粘住?

4

4 回答 4

6

The problem is the place you're drawing to isn't persistant. At any moment, you can lose everything you've drawn to it. The paint(Graphics) method is called when this happens. You'll either need to repaint the entire picture every time this happens, or you'll need to set aside a canvas to draw to and copy the contents to your applet's Graphics as needed.

Here's how to create and draw to an image:
http://java.sun.com/docs/books/tutorial/2d/images/drawonimage.html

Then, in your paint method, use your Graphics' drawImage(...) method to display the image you've created.

于 2009-11-26T06:11:38.777 回答
6

我不知道我是否正确地阅读了这个,但为什么不将最后一次点击的位置存储在一个变量中,以便稍后在调用 paint() 方法时进行绘制?

于 2009-11-26T06:03:19.607 回答
0

The Graphics is temporary. When a region gets dirty, it will be repainted.

The best way is to create a BufferedImage, paint to it on mousePressed and call repaint.
When paint is called, draw the Image onto the passed Graphics Object. This way you don't need to store the Rectangles and you got a buffer which will improve performance.

于 2009-11-26T09:07:59.513 回答
0

您必须覆盖窗口调整大小动作侦听器并在其中调用 repaint。

于 2009-11-26T06:03:05.707 回答