1

我试图让我的自定义光标的热点到我的 .png 图像的中心,但我似乎无法弄清楚如何。目前我的编码技能很差,但我会尝试任何事情!

public void setCursor(String filename) {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Image cursorIcon = toolkit.getImage(filename);
    Image cursorIconScaledInstance = cursorIcon.getScaledInstance(60, 60, Image.SCALE_FAST);
    cursor = toolkit.createCustomCursor(cursorIconScaledInstance, new Point(30, 30), "cursor");
    seedButtonPanel.setCursor(cursor);
}
4

1 回答 1

2

不知道你能不能把游标做成那么大。

下面是一个使用 BufferedImage 作为光标图像创建自定义光标的示例:

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class PaintBrushCursor
{
    public static Cursor createCursor(int brushSize)
    {
        Dimension bestSize = Toolkit.getDefaultToolkit().getBestCursorSize(0, 0);

        BufferedImage image = new BufferedImage(bestSize.width, bestSize.height, BufferedImage.TYPE_INT_ARGB );
        Graphics2D g2d = (Graphics2D)image.getGraphics();
        g2d.setColor( Color.BLACK );

        //  draw center point

        int ovalX = (bestSize.width - brushSize) / 2;
        int ovalY = (bestSize.height - brushSize) / 2;

        g2d.fillOval(ovalX, ovalY, brushSize, brushSize);

        //  draw guidelines

        int centerX = bestSize.width / 2;
        int centerY = bestSize.height / 2;
        int offset = (brushSize / 2) + 5;
        int length = 5;

        g2d.drawLine(centerX - offset - length, centerY, centerX - offset, centerY);
        g2d.drawLine(centerX + offset, centerY, centerX + offset + length, centerY);

        g2d.drawLine(centerX, centerY - offset - length, centerX, centerY - offset);
        g2d.drawLine(centerX, centerY + offset, centerX, centerY + offset + length);

        Point hotSpot = new Point(centerX, centerY);

        return Toolkit.getDefaultToolkit().createCustomCursor(image, hotSpot, "PaintBrush" );
    }

    private static void createAndShowGUI()
    {
        JPanel panel = new JPanel();
        panel.setCursor( PaintBrushCursor.createCursor(7) );

        JFrame frame = new JFrame("Paint BrushC ursor");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( panel );
        frame.setLocationByPlatform( true );
        frame.setSize(200, 200);
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}
于 2018-05-19T21:54:46.460 回答