在 JAVA 中重新绘制小程序而不会丢失以前的内容 [英] Repaint Applets in JAVA without losing previous contents
本文介绍了在 JAVA 中重新绘制小程序而不会丢失以前的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以重新绘制小程序而不丢失其先前的内容?我只是想制作一个程序,允许用户使用鼠标绘制线条、矩形等.我使用了重绘方法,但它不保留以前绘制的线条/矩形等.
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.
这是片段:
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循环,绘制所有点,或者有时更好 - 连接连续点的线.
- Draw to a BufferedImage using the Graphics object obtained from it via
getGraphics()
, and then draw the BufferedImage in your JPanel'spaintComponent(Graphics g)
method. Or - Create an
ArrayList<Point>
place your mouse points into the List, and then in the JPanel'spaintComponent(Graphics g)
method, iterate through the List with a for loop, drawing all the points, or sometimes better -- lines that connect the contiguous points.
其他重要建议:
- 确保您使用的是 Swing 库(JApplet、JPanel),而不是 AWT(Applet、Panel、Canvas).
- 如果可能,您最好避免使用小程序.
- 不要在paint方法中绘制,而是在JPanel的
paintComponent(Graphics g)
方法中绘制. - 不要忘记在您的
paintComponent(Graphics g)
方法覆盖中首先调用 super 的方法.
- 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 中重新绘制小程序而不会丢失以前的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文