在mouseMoved中调用repaint时光标消失了?

时间:2012-08-30 17:28:09

标签: java swing graphics paintcomponent mousemove

我在光标移动时从光标位置绘制水平和垂直线时遇到问题。光标似乎消失了。

我已将一个MouseInputAdapter附加到我的swing组件,该组件有一个调用repaint()的mouseMoved方法;

调用重绘将导致调用paintComponent(Graphics g)。在paintComponent中,我绘制水平和垂直线:

Dimension dim = getSize();
g2.setColor(Color.white);
g2.fillRect(0, 0, dim.width, dim.height);
g2.setColor(Color.black);
Point pos = this.getMousePosition();
g2.draw(new Line2D.Double(0, pos.y, dim.getWidth(), pos.y));
g2.draw(new Line2D.Double(pos.x, 0, pos.x, dim.getHeight()));

以下是截图:

enter image description here

光标应位于大水平线和垂直水平线之间的白色区域,并且应位于大数字1.2434307的左侧...

当我用鼠标移动光标时,我可以看到光标(十字准线)闪烁,这让我相信我的绘画方法是在光标上画画。

任何人都知道问题可能在哪里?

根据要求,我添加了一些测试代码。

public class TestApp extends JFrame {
public TestApp() {
    super("TestApp");

    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(new CustomComponent(), BorderLayout.CENTER);
    this.setSize(300, 300);
    this.setVisible(true);

}

class CustomComponent extends JComponent {
    public CustomComponent() {
        setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

        MouseInputAdapter mia = new MouseInputAdapter() {

            @Override
            public void mouseMoved(MouseEvent e) {
                repaint();
            }

        };

        addMouseMotionListener(mia);
        addMouseListener(mia);
    }

    @Override
    public void paintComponent(Graphics g) {
        Dimension dim = getSize();
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(Color.white);
        g2.fillRect(0, 0, dim.width, dim.height);


        g2.setColor(Color.black);
        Point pos = this.getMousePosition();
        if (pos != null) {

            g2.draw(new Line2D.Double(0, pos.y, dim.getWidth(), pos.y));
            g2.draw(new Line2D.Double(pos.x, 0, pos.x, dim.getHeight()));
            g2.drawString("where is my cursor?", pos.x, pos.y);
        }
    }
}

public static void main(String[] args) {
    new TestApp();
}
}

0 个答案:

没有答案