2

I'm changing a cursor, using a PNG image (with transparency), but when I run the code below, the image doesn't look like it should.

public void CustomCursor()
{
    Toolkit t1 = Toolkit.getDefaultToolkit();
    Image img = t1.getImage("src/AppImages/Cursor1.png");
    Point point = new Point(0,0);
    Cursor cursor = t1.createCustomCursor(img, point, "Cursor");
    setCursor(cursor);    
}

This method is called in the Jframe's constructor.

enter image description here

This is the cursor1.png image, sized 25x25px.

After running the code:

enter image description here

enter image description here

enter image description here

If I use cursor1.png as a JLabel, it looks OK:

enter image description here

MCVE

import java.awt.*;
import java.net.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class CustomCursor {

    private JComponent ui = null;

    CustomCursor() {
        initUI();
    }

    public void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(20, 200, 20, 200));
        Toolkit t1 = Toolkit.getDefaultToolkit();
        Image img;
        try {
            URL url = new URL("https://i.stack.imgur.com/sJKuE.png");
            img = t1.getImage(url);
            Point point = new Point(0, 0);
            Cursor cursor = t1.createCustomCursor(img, point, "Cursor");
            ui.setCursor(cursor);
            ui.add(new JLabel(new ImageIcon(url)));
        } catch (MalformedURLException ex) {
            Logger.getLogger(CustomCursor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                CustomCursor o = new CustomCursor();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

Can anyone tell why that happens?

Community
  • 1
  • 1
Zujaj Misbah Khan
  • 655
  • 2
  • 11
  • 31

1 Answers1

2

The issue is Windows; transparent pixels just aren't taken into account.

There is a really good answer on how to fix this on this post. Another good answer here.

Community
  • 1
  • 1
Matthew Meacham
  • 403
  • 3
  • 9