我正在创建一个看起来像这样的动画。
我希望左侧的漩涡状图标(这是一个 ImageIcon)显示 3 秒钟然后消失。但是,漩涡状图标不会消失。
这是我的代码。
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("random title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public int x;
public int y;
public int remoteControllerX = 473;
public int remoteControllerY = 340;
public int buttonX = 166;
public int buttonY = 208;
Image img;
Image remoteController;
ImageIcon button = new ImageIcon("graphics/button.gif");
Component buttonTrigger = this;
public MyPanel() {
try {
img = ImageIO.read(new File("graphics/close_0.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
try {
remoteController = ImageIO.read(new File("graphics/pilot.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setBorder(BorderFactory.createLineBorder(Color.black));
new Timer(3000, paintTimer).start();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
// Here goes action on background, which is unrelated to this example.
}
});
}
public Dimension getPreferredSize() {
return new Dimension(1048, 484);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
g.drawImage(remoteController, remoteControllerX, remoteControllerY, null);
Toolkit.getDefaultToolkit().sync();
button.paintIcon(buttonTrigger, g, buttonX, buttonY);
}
Action paintTimer = new AbstractAction() {
private static final long serialVersionUID = -2121714427110679013L;
public void actionPerformed(ActionEvent e) {
buttonTrigger = null;
repaint();
}
};
}
您还需要这 3 个图像才能运行代码:
http://ajks.pl/graveyard/close_0.jpg
http://ajks.pl/graveyard/pilot.png
http://ajks.pl/graveyard/button.gif
它们被放置在主 Java 项目下的图形文件夹中。