在JAVA中重绘Applet而不会丢失以前的内容

时间:2014-05-28 03:32:59

标签: 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);

}

2 个答案:

答案 0 :(得分:2)

两种可能的解决方案:

  1. 使用通过getGraphics()从它获取的Graphics对象绘制到BufferedImage,然后在JPanel的paintComponent(Graphics g)方法中绘制BufferedImage。或
  2. 创建一个ArrayList<Point>位置,鼠标指向List,然后在JPanel的paintComponent(Graphics g)方法中,使用for循环迭代List,绘制所有点,或者有时更好 - 行连接连续点。
  3. 其他重要建议:

    • 确保您使用的是Swing库(JApplet,JPanel),而不是AWT(Applet,Panel,Canvas)。
    • 如果可能的话,最好避免使用applet。
    • 不要使用绘画方法绘制,而是绘制JPanel的paintComponent(Graphics g)方法。
    • 不要忘记在paintComponent(Graphics g)方法覆盖中首先调用超级方法。

答案 1 :(得分:1)

你需要跟踪已绘制的所有内容,然后再重新绘制所有内容。

有关实现此目的的两种常用方法,请参阅Custom Painting Approaches

使用ArrayList跟踪绘制的对象 使用BufferedImage

这是您可以使用的代码示例:

ArrayList<Point> points = new ArrayList<Point>();
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