gpt4 book ai didi

java - 两个图像之间快速切换?

转载 作者:行者123 更新时间:2023-12-02 00:06:49 26 4
gpt4 key购买 nike

我想使用两个快速切换的图像来制作一个张开嘴和闭上嘴的对象。我尝试使用 for 循环,但它落后于我的游戏。

 if(direction == Constant.UP){

ImageIcon i = new ImageIcon("src\\images\\pacman up.png");
image = i.getImage();

ImageIcon i2 = new ImageIcon("src\\images\\pacman left.png");
image = i2.getImage();

}
G.drawImage(image, x, y, 20,20,null);

最佳答案

Swing 中的任何动画都需要考虑 Event Dispatching Thread .

您不应该在 EDT 的内容中执行任何可能阻止它的操作(例如循环或 I/O),因为这将阻止 EDT(除其他外)处理绘制请求。

您应该始终使用能够支持双缓冲区的表面,例如JPanel,因为这将有助于消除闪烁

下面使用javax.swing.Timer在两个图像之间切换...

enter image description here enter image description here

public class TestPacMan {

public static void main(String[] args) {
new TestPacMan();
}

public TestPacMan() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new PacManPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class PacManPane extends JPanel {

private BufferedImage pacOpened;
private BufferedImage pacClosed;
private BufferedImage frame;
private boolean opened = true;

public PacManPane() {
try {
pacOpened = ImageIO.read(new File("PC-Closed.png"));
pacClosed = ImageIO.read(new File("PC-Opened.png"));
frame = pacOpened;
} catch (IOException exp) {
exp.printStackTrace();
}

Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
opened = !opened;
frame = opened ? pacOpened : pacClosed;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();

}

@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (frame != null) {
int x = (getWidth() - frame.getWidth()) / 2;
int y = (getHeight() - frame.getHeight()) / 2;
g2d.drawImage(frame, x, y, this);
}
g2d.dispose();
}

}

}

关于java - 两个图像之间快速切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com