在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< Point>将鼠标点放入List,然后在JPanel的paintComponent(Graphics g)方法中,使用for循环遍历List,绘制所有点,或者有时更好 – 连接连续点的线.

其他重要建议:

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

上一篇:Java小程序和JavaScript


下一篇:HDU_4826