最近,我学习了Java中的BufferedImage类,并应用该概念创建了一个简单的Java绘画应用程序。但是我无法在面板上绘制任何曲线。我查看了网上其他缓冲图像示例,但似乎都无法在我的代码上工作。我是否正确使用了BufferedImage?我该如何修复我的代码?
欢迎更改我的源代码。
PaintBoard类:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintBoard extends JPanel implements MouseMotionListener, MouseListener {
private BufferedImage canvas = new BufferedImage(600, 400, BufferedImage.TYPE_INT_RGB);
private boolean painting;
private int prevX, prevY, curX, curY;
Color canvasColour = Color.WHITE;
int brushSize = 6;
int brushType = 1;
Color currentColour = Color.BLACK;
public PaintBoard() {
setSize(getWidth(), getHeight());
addMouseMotionListener(this);
addMouseListener(this);
}
@Override
public void paintComponent(Graphics board) {
super.paintComponent(board);
board.setColor(canvasColour);
board.fillRect(0, 0, getWidth(), getHeight());
board.drawImage(canvas, 600, 400, this);
}
private void updateBoard() {
Graphics2D paintBrush = canvas.createGraphics();
paintBrush.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
paintBrush.setPaint(currentColour);
paintBrush.setStroke(new BasicStroke(brushSize, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
paintBrush.drawLine(prevX, prevY, curX, curY);
repaint();
}
public void mouseDragged(MouseEvent e) {
if (!painting)
return;
curX = e.getX();
curY = e.getY();
updateBoard();
prevX = curX;
prevY = curY;
}
public void mousePressed(MouseEvent e) {
if (painting)
return;
prevX = e.getX();
prevY = e.getY();
painting = true;
}
public void mouseReleased(MouseEvent e) {
if (!painting)
return;
curX = e.getX();
curY = e.getY();
painting = false;
}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
绘画应用:
import javax.swing.*;
public class paintApp extends JApplet {
public void init() {
this.setSize(600, 400);
this.setContentPane(new PaintBoard());
}
}