我正在尝试制作一个小的绘画应用程序,在其中输入所需的颜色并更改画笔的大小。我做到了,而且能正常工作,但是如果我尝试快速绘制,则该应用程序不会在短时间内更新,留下的点看起来像这样:
每秒 60次(因为每秒60次应该足以不留点/缝隙。请参阅刻度方法。作为测试,我尝试设置了 no 限制在ticksPerSecond上,并且得到相同的输出),如果用户引起了mouseDragged
或mousePressed
事件,我将添加一个Circle
类的实例(如下所示)>
class Circle {
int x, y;
int radius;
Color color;
Circle(int x, int y, int radius, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
}
我的勾号方法:(每秒调用60次)
private void tick() {
this.middle = this.brush.radius / 2; // Used because java.awt.Graphics will paint from your cursors xy, which will paint the circle down and to the right of the cursor
if (this.frame.isDragging) {
add(new Circle(this.frame.x - this.middle, this.frame.y - this.middle, this.brush.radius, this.brush.color));
}
}
要渲染,我只需运行一个foreach
循环,如下所示
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // Paint over everything else
try {
for (Circle circle : this.circles) {
g.setColor(circle.color);
g.fillOval(circle.x, circle.y, circle.radius, circle.radius);
}
} catch (ConcurrentModificationException ignore) {} //TODO MAKE THIS BETTER
}
忽略我正在捕获ConcurrentModifictionException
,这是一个临时解决方案,因为我要添加到此处正在读取的列表中。 (它只会在我绘画时使油漆闪烁,因此现在可以使用)
有人要求我提供框架,就在这里(您可能不需要它,但是我包含了所需的任何代码。删除了我不使用的implement methods
):
class Frame extends JFrame implements MouseListener, MouseMotionListener {
int x, y;
boolean isDragging, isMouseOnScreen;
Frame(int width) {
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.getContentPane().setPreferredSize(new Dimension(width, width / 3 * 2));
this.setResizable(false);
this.pack();
this.setLocationRelativeTo(null);
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Cursor cursor = this.getToolkit().createCustomCursor(image, new Point(0, 0), "Cursor");
this.setCursor(cursor);
this.setFocusable(true);
this.requestFocus();
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.x = this.y = 0;
this.isDragging = this.isMouseOnScreen = false;
}
@Override
public void mouseDragged(MouseEvent e) {
this.x = e.getX() - 5;
this.y = e.getY() - 35;
}
@Override
public void mouseMoved(MouseEvent e) {
this.x = e.getX() - 5;
this.y = e.getY() - 35;
}
@Override
public void mousePressed(MouseEvent e) {
this.isDragging = true;
}
@Override
public void mouseReleased(MouseEvent e) {
this.isDragging = false;
}
@Override
public void mouseEntered(MouseEvent e) {
isMouseOnScreen = true;
}
@Override
public void mouseExited(MouseEvent e) {
isMouseOnScreen = false;
}
}