我正在使用 PNG 图像(具有透明度)更改光标,但是当我运行下面的代码时,图像看起来并不像它应该的那样。
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);
}
此方法在 Jframe 的构造函数中调用。
这是 cursor1.png
图像,大小为 25x25px。
运行代码后:
如果我使用 cursor1.png
作为 JLabel
,它看起来没问题:
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("/image/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);
}
}
谁能告诉我为什么会发生这种情况吗?
最佳答案
关于java - Swing:如何将自定义光标设置为透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32202747/