Frage

Ich habe Java Swing Chess-Anwendung.Der Cursor verfügt über individuelle Ansicht - Rechteck, Größe, um die gesamte Zelle anzupassen.Und ich brauche Cursor, der sich nur über ganze Zelle bewegt.Nicht in den Grenzen einer Zelle.Gibt es typische Lösungen für dieses Problem?Oder Vielleicht ist es möglich, mit Standard-Java-Funktionen Schritt-Typ-Cursor zu setzen?

Bildbeschreibung hier eingeben

War es hilfreich?

Lösung

I wouldn't implement some kind of "stepping" cursor. Instead I would hide the cursor completly and highlight the current cell programmatically.


Full example below that "outputs" this screenshot:

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);
        }
    }
}

And some test code:

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);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top