在JAVA中重绘Applet而不会丢失以前的内容
是否可以在不丢失其先前内容的情况下重新绘制applet? 我只是想制作一个允许用户使用鼠标绘制线条,矩形等的程序。 我使用了重绘方法,但它没有保留先前绘制的线条/矩形等。
这是片段:
public void mousePressed(MouseEvent e){x1=e.getX();y1=e.getY();} public void mouseDragged(MouseEvent e) { x2=e.getX(); y2=e.getY(); repaint(); showStatus("Start Point: "+x1+", "+y1+" End Point: "+x2+", "+y2); } public void paint(Graphics g) { //g.drawLine(x1,y1,x2,y2); g.drawRect(x1, y1, x2-x1, y2-y1); }
两种可能的方案:
- 使用通过
getGraphics()
从它获得的Graphics对象绘制到BufferedImage,然后在JPanel的paintComponent(Graphics g)
方法中绘制BufferedImage。 要么 - 创建一个
ArrayList
将鼠标指向List,然后在JPanel的paintComponent(Graphics g)
方法中,使用for循环迭代List,绘制所有点,或者有时更好 – 连接连续的行点。
其他重要建议:
- 确保您使用的是Swing库(JApplet,JPanel),而不是AWT(Applet,Panel,Canvas)。
- 如果可能的话,最好避免使用applet。
- 不要绘制paint方法,而是绘制JPanel的
paintComponent(Graphics g)
方法。 - 不要忘记在
paintComponent(Graphics g)
方法覆盖中首先调用super的方法。
您需要跟踪已绘制的所有内容,然后重新绘制所有内容。
有关执行此操作的两种常用方法,请参阅自定义绘制方法 :
使用ArrayList跟踪绘制的对象使用BufferedImage
这是您可以使用的代码示例:
ArrayList points = new ArrayList (); private void draw(Graphics g){ for (Point p: this.points){ g.fillOval(1, 2, 2, 2); } } //after defining this function you add this to your paint function : draw(g) g.drawRect(x1, y1, x2-x1, y2-y1); points.add(new Point(x1, y1, x2-x1, y2-y1)) // PS : point is a class I created to refer to a point, but you can use whatever