Java - 将自定义光标热点设置为图像中心(.png)

时间:2018-05-19 20:47:39

标签: java custom-cursor

我正在尝试将自定义光标的热点放到我的.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);
}

1 个答案:

答案 0 :(得分:0)

不知道你是否可以制作一个大的光标。

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

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();
            }
        });
*/
    }
}