重绘在JAVA小程序,而不会丢失previous内容 [英] Repaint Applets in JAVA without losing previous contents

查看:111
本文介绍了重绘在JAVA小程序,而不会丢失previous内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能重新画一个小程序,而不会失去它的previous内容是什么?我只是试图让一个程序,它允许用户绘制线条,矩形等使用鼠标。我已经使用了重新绘制方法,但它不守previously绘制的线条/矩形等。

下面是片段:

 公共无效鼠标pressed(的MouseEvent E){X1 = e.getX(); Y1 = e.getY();}
公共无效的mouseDragged(的MouseEvent E)
{
    X2 = e.getX();
    Y2 = e.getY();
    重绘();
    showStatus(开始点:+ X1 +,+ Y1 +终点:+ 2 +,+ Y2);
}
公共无效漆(图形G)
{
    //g.drawLine(x1,y1,x2,y2);
    g.drawRect(X1,Y1,X2-X1,Y2-Y1);}


解决方案

有两种可能的解决方案:


  1. 使用图形通过从该对象获取的getGraphics()绘制到一个BufferedImage,然后绘制的BufferedImage在JPanel中的的paintComponent(图形摹)方法。或

  2. 创建一个的ArrayList<点> 将鼠标点到列表,然后在JPanel的的paintComponent(图形G)方法,遍历一个for循环的清单,绘制所有点,或有时更好 - 连接相邻点线

其他重要建议:


  • 请确保您使用的Swing库(JApplet的,JPanel中),而不是AWT(小程序,面板,帆布)。

  • 你最好避免小程序,如果在所有可能的。

  • 请不要在paint方法绘制,而是一个JPanel的的paintComponent(图形G)方法。

  • 请不要忘了调用超类的方法,第一件事就是在你的的paintComponent(图形G)方法重写。

Is it possible to re-paint an applet without losing its previous contents? I was just trying to make a program which allows users to draw lines, Rectangle etc. using mouse. I have used the repaint method but it does not keep the previously drawn lines/rectangles etc.

Here is the snippet:

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);

}

解决方案

Two possible solutions:

  1. Draw to a BufferedImage using the Graphics object obtained from it via getGraphics(), and then draw the BufferedImage in your JPanel's paintComponent(Graphics g) method. Or
  2. Create an ArrayList<Point> place your mouse points into the List, and then in the JPanel's paintComponent(Graphics g) method, iterate through the List with a for loop, drawing all the points, or sometimes better -- lines that connect the contiguous points.

Other important suggestions:

  • Be sure that you're using the Swing library (JApplet, JPanel), not AWT (Applet, Panel, Canvas).
  • You're better off avoiding applets if at all possible.
  • Don't draw in a paint method but rather a JPanel's paintComponent(Graphics g) method.
  • Don't forget to call the super's method first thing in your paintComponent(Graphics g) method override.

这篇关于重绘在JAVA小程序,而不会丢失previous内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆