问题描述
我有一个Java绘画程序,该程序使用自定义的JPanel进行绘画.当单击JPanel时,会绘制一个小的椭圆形(或圆形,如果您愿意的话),则每次单击另一个位置时,椭圆形都会消失.坐标也会更新,但是椭圆形不会停留,它会移动到用户单击下一步的位置.这是自定义JPanel的代码:
I have a Java paint program that uses a custom JPanel to paint on. While when clicking on the JPanel paints a small oval (or circle, if you will), the oval disappears each time you click on another place. The coordinates also get updated, but the oval does not stay, it moves to wherever the user clicks next...Here's the code for the custom 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) {
}
}
我需要按住鼠标才能连续绘制椭圆形,直到放开鼠标按钮为止.唯一的问题是椭圆形鼠标会更新,但不会保存其原始位置.我该如何解决?
I need the holding of a mouse to continuously paint an oval until the mouse button is let go. The only problem here is that the mouse oval updates, but does not save it's original position. How do I fix this?
推荐答案
仅绘制一个椭圆,因为在paintComponent
方法中只有一个fillOval
语句绘制了一个椭圆,因此该语句
Only one oval is drawn as there is only one fillOval
statement drawing a single oval in the paintComponent
method so the statement
super.paintComponent(g);
一旦调用repaint
,将清除所有先前的绘画.
causes any previous painting to be cleared once repaint
is called.
要绘制多个椭圆,您可以按照自定义绘画方法
To paint multiple ovals, you can paint components from a List<Point>
as outlined in Custom Painting Approaches
请勿从paintComponent
内部调用repaint
.这将导致无限循环并降低性能.如果需要定期更新,请从 Swing的ActionListener
调用repaint
.计时器.
Don't call repaint
from within paintComponent
. This creates an infinite loop and degrades performance. If periodic updates are required invoke repaint
from the ActionListener
of a Swing Timer instead.
这篇关于为什么此Java Paint程序不能绘制多个椭圆形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!