我有一个使用自定义 JPanel 进行绘画的 Java 绘画程序。当单击 JPanel 时会绘制一个小椭圆(或圆形,如果您愿意的话),但每次单击另一个位置时椭圆会消失。坐标也会更新,但椭圆不会停留,它会移动到用户接下来单击的任何位置...这是自定义 JPanel 的代码:
int xCord, yCord;
public class PaintPanel extends JPanel implements MouseListener {
// default serial whatever...
private static final long serialVersionUID = -6514297510194472060L;
// initial values
int xCord = -10;
int yCord = -10;
public PaintPanel() {
addMouseListener(this);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(ProgramUI.currentColor);
g.fillOval(xCord, yCord, 8, 8);
repaint();
}
@Override
public void mouseClicked(MouseEvent m) {
}
@Override
public void mouseEntered(MouseEvent m) {
}
@Override
public void mouseExited(MouseEvent m) {
}
@Override
public void mousePressed(MouseEvent m) {
if (paintPanel.contains(m.getPoint())) {
xCord = m.getX();
yCord = m.getY();
System.out.println("x: " + xCord + " y: " + yCord);
}
}
@Override
public void mouseReleased(MouseEvent m) {
}
}
我需要按住鼠标来连续绘制椭圆,直到松开鼠标按钮。这里唯一的问题是鼠标椭圆更新,但不保存它的原始位置。我该如何解决?