我正在学习摆动图形,我想尝试在java中更改光标颜色。所以我下载了一些金色星星的gif文件试图用于我的光标,但是当我将图像添加为ImageIcon时,它变成了星星'颜色变黑。
编辑:更改语法
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class stuff {
public static void main (String[] args)
{
JFrame frame = new JFrame("FRAME");
JPanel lpanel = new JPanel();
frame.setContentPane(lpanel);
ImageIcon goldStar = new ImageIcon("./res/goldStar.gif");
JLabel gs = new JLabel(goldStar);
lpanel.add(gs);
goldStar = new ImageIcon(goldStar.getImage().getScaledInstance((int)(goldStar.getIconWidth()/13), (int)(goldStar.getIconHeight()/13), Image.SCALE_SMOOTH));
lpanel.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(goldStar.getImage(),new Point(0,0), "custom cursor"));
//I think these two lines are creating the problem.
lpanel.setPreferredSize(new Dimension(1600,900));
frame.setVisible(true);
frame.pack();
}
}
我查看了光标的一些方法,但我找不到任何可以帮助我的方法。
答案 0 :(得分:3)
您可以按照here所述加载gif图像的帧并循环它们。
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
private int currentIndex;
public Main() throws IOException {
JFrame frame = new JFrame("FRAME");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.setContentPane(panel);
List<Cursor> cursors = new ArrayList<>();
List<BufferedImage> frames = getFrames("GWigb.gif");
for (BufferedImage image : frames) {
cursors.add(Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "cursor image"));
}
Timer timer = new Timer(50, (actionEvent) -> {
panel.setCursor(cursors.get(currentIndex++));
if (currentIndex >= cursors.size())
currentIndex = 0;
});
timer.start();
panel.setPreferredSize(new Dimension(1600, 900));
frame.setVisible(true);
frame.pack();
}
public List<BufferedImage> getFrames(String gif) throws IOException {
List<BufferedImage> frames = new ArrayList<>();
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
File input = new File(gif);
ImageInputStream stream = ImageIO.createImageInputStream(input);
reader.setInput(stream);
int count = reader.getNumImages(true);
for (int index = 0; index < count; index++) {
frames.add(reader.read(index));
}
return frames;
}
public static void main(String[] args) throws IOException {
new Main();
}
}
答案 1 :(得分:2)
您应该考虑使用非动画图片,因为Toolkit.createCustomCursor的文档指出:
请注意,多帧图像无效,可能导致此方法 挂起。
或者,您可以使用一组Cursor
个对象(在您的情况下为自定义对象),并在Thread
中创建动画。