package _11;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class PaintFrame extends JFrame {
// 记录绘图内容的缓冲区
private BufferedImage canvas;
// 记录上一次鼠标的x、y位置
private int lastX = -1;
private int lastY = -1;
public PaintFrame() {
// 窗口大小改变事件:适配缓冲区大小并保留原有绘图
this.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
BufferedImage newCanvas = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
if (canvas != null) {
Graphics g = newCanvas.getGraphics();
g.drawImage(canvas, 0, 0, null);
}
canvas = newCanvas;
}
});
// 鼠标移动事件:绘制连续红线
this.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if (lastX == -1 && lastY == -1) {
// 初始化首次鼠标位置
lastX = x;
lastY = y;
} else {
// 在缓冲区绘制红线
Graphics g = canvas.getGraphics();
g.setColor(Color.RED);
g.drawLine(lastX, lastY, x, y);
// 更新鼠标位置
lastX = x;
lastY = y;
// 触发界面重绘
repaint();
}
}
});
}
// 重写paint方法:将缓冲区内容绘制到窗口
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(canvas, 0, 0, null);
}
public static void main(String[] args) {
PaintFrame frame = new PaintFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
1962

被折叠的 条评论
为什么被折叠?



