摆动步进式光标移动

时间:2012-01-26 14:39:07

标签: java swing graphics paintcomponent mouselistener

我有java swing chess应用程序。游标具有自定义视图 - 矩形,大小适合整个单元格。我需要光标只在整个单元格上移动。不在一个细胞的范围内。这个问题有一些典型的解决方案吗?或者也许可以设置标准的java功能步进式光标移动?

enter image description here

1 个答案:

答案 0 :(得分:6)

我不会实现某种“踩”光标。相反,我会完全隐藏光标并以编程方式突出显示当前单元格。


下面的完整示例“输出”此屏幕截图:

screenshot

public class StepComponent extends JComponent implements MouseMotionListener {
    private Point point = new Point(0, 0);

    public StepComponent() {
        setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
                new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB), 
                new Point(0, 0), "blank cursor"));
        addMouseMotionListener(this);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int x = 0, y = 0;
        while (x < getWidth()) { g.drawLine(x, 0, x, getHeight()); x += 10; }
        while (y < getHeight()) { g.drawLine(0, y, getWidth(), y); y += 10; }
        if (point != null)
            g.fillRect(point.x, point.y, 10, 10);
    }
    @Override public void mouseDragged(MouseEvent e) { update(e.getPoint()); }
    @Override public void mouseMoved(MouseEvent e) { update(e.getPoint()); }

    private void update(Point p) {
        Point point = new Point(10 * (p.x / 10), 10 * (p.y / 10));
        if (!this.point.equals(point)) {
            Rectangle changed = new Rectangle(this.point,new Dimension(10,10));
            this.point = point;
            changed.add(new Rectangle(this.point, new Dimension(10, 10)));
            repaint(changed);
        }
    }
}

还有一些测试代码:

public static void main(String[] args) {

    JFrame frame = new JFrame("Test");

    frame.add(new StepComponent());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}