我们最近开始使用Applet并用它做事,所以最后一堂课是绘图线。因此,在写完一个成功的代码之后,我出于某种原因改变了一行代码,而我现在并不知道这一行,而是绘制一条奇怪的光线。这是代码所以任何帮助将不胜感激。
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class SimplePaint extends Applet {
private int lastx;
private int lasty;
@Override
public void init() {
this.setForeground(Color.BLUE);
this.addMouseListener(new PositionRecorder());
this.addMouseMotionListener(new LineDrawer());
}
public int getLastx() {
return lastx;
}
public void setLastx(int lastx) {
this.lastx = lastx;
}
public int getLasty() {
return lasty;
}
public void setLasty(int lasty) {
this.lasty = lasty;
}
private class PositionRecorder extends MouseAdapter{
public void mousePressed(MouseEvent e) {
setLastx(e.getX());
setLasty(e.getY());
}
}
private class LineDrawer extends MouseMotionAdapter{
public void mouseDragged(MouseEvent e) {
int x=e.getX();
int y=e.getY();
Graphics g;
g=getGraphics();
g.drawLine(lastx, lasty, x, y);
}
}
}
我特别记得如果有帮助的话,搞乱这部分代码
private class PositionRecorder extends MouseAdapter{
public void mousePressed(MouseEvent e) {
setLastx(e.getX());
setLasty(e.getY());
AWT中的绘画是一个记录良好的过程。你应该从阅读开始:
“近距离观察油漆机制”的行情
paint方法(由java.awt.Component定义。)只要需要渲染组件,此方法将由绘制子系统执行。
在AWT中,绘画具有破坏性,预计随时调用paint
,您将完全重绘组件状态。这引发了一些您需要解决的问题。
对于你需要绘制的任何东西,你需要一种可靠的方法来存储这些状态,并在调用paint
时重新应用它们。在你的情况下,像ArrayList
这样简单的东西是合适的,但你也可以使用BufferedImage
作为后备缓冲区并将提交的绘图元素绘制到它。
第一种方法的好处是提供撤消更改的能力,但就绘画而言,并不像简单地绘制图像那么快。
更聪明的方法是使用两者。维持绘制状态在ArrayList
中,渲染每个像BufferedImage
一样,当你想要执行撤消时,从一个新的BufferedImage
开始并将所有状态绘制到你不需要的点......但那是超出了问题的范围
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class SimplePaint extends Applet {
private Point clickPoint;
private Point dragPoint;
@Override
public void init() {
this.setForeground(Color.BLUE);
this.addMouseListener(new PositionRecorder());
this.addMouseMotionListener(new LineDrawer());
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (clickPoint != null && dragPoint != null) {
g.drawLine(clickPoint.x, clickPoint.y, dragPoint.x, dragPoint.y);
}
}
private class PositionRecorder extends MouseAdapter {
public void mousePressed(MouseEvent e) {
clickPoint = e.getPoint();
}
@Override
public void mouseReleased(MouseEvent e) {
// This is where I'd reset the clickPoint and dragPoint
// to null and apply the line to some structure which can
// redraw it in the `paint` method, maybe something like
// a ArrayList
// Alternativly, you could render the result to a BufferedImage
// and paint that inside the paint method
}
}
private class LineDrawer extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
repaint();
}
}
}