我试图在我的 JPanel 内绘图,但每次单击时,我的 JPanel 的背景都会消失。它在鼠标所在的位置画一条线。我认为这与 2D 图形有关有人可以帮忙吗?
public Brush() {
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.white);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2;
// super.paintComponent(g);
g2 = (Graphics2D) g;
g2.setColor(brushColor);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(8, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
//Ellipse2D.Double circle = new Ellipse2D.Double(p1.x,p1.y,20,20);
g2.fillOval(p1.x,p1.y,20,20);
}
@Override
public void mousePressed(MouseEvent e) {
dragging = true;
p1 = e.getPoint();
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
dragging = false;
p1 = e.getPoint();
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
if (dragging) {
p1 = e.getPoint();
repaint();
}
}