在java中切换imageIcon?

我有许多在窗口中移动的平面(线程),我想根据平面的方向切换ImageIcon。 例如:如果一个平面向右移动,则该平面的imageIcon是正确的,然后平面向左移动,交换该平面的imageIcon。 我怎么能在paintComponent方法中做到这一点? 对不起,我的英语不好。

如果您正在讨论交换JLabel显示的ImageIcon,那么您不应该在paintComponent中切换ImageIcons,而应该在非paintComponent代码区域中执行此操作,可能在Swing Timer中。 即使您不是在讨论JLabel,也不应使用paintComponent方法来更改对象的状态。

然而,你的问题太多没有说明,让我们能够完全和好地回答它。 考虑告诉并展示更多内容。

如果你正在寻找一个逻辑的东西,那么这里有一个小例子,尽管你可能需要根据自己的需要进行修改。

 import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.util.Random; import javax.swing.*; public class FlyingAeroplane { private Animation animation; private Timer timer; private ActionListener timerAction = new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { animation.setValues(); } }; private void displayGUI() { JFrame frame = new JFrame("Aeroplane Flying"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); animation = new Animation(); frame.setContentPane(animation); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); timer = new Timer(100, timerAction); timer.start(); } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new FlyingAeroplane().displayGUI(); } }); } } class Animation extends JPanel { private final int HEIGHT = 150; private final int WIDTH = 200; private int x; private int y; private ImageIcon image; private boolean flag; private Random random; public Animation() { x = 0; y = 0; image = new ImageIcon(getClass().getResource("/image/aeroplaneright.jpeg")); flag = true; random = new Random(); } public void setValues() { x = getXOfImage(); y = random.nextInt(70); repaint(); } private int getXOfImage() { if (flag) { if ((x + image.getIconWidth()) == WIDTH) { flag = false; x--; return x; } x++; image = new ImageIcon(getClass().getResource("/image/aeroplaneright.jpeg")); } else if (!flag) { if (x == 0) { flag = true; x++; return x; } x--; image = new ImageIcon(getClass().getResource("/image/aeroplaneleft.jpeg")); } return x; } @Override public Dimension getPreferredSize() { return (new Dimension(WIDTH, HEIGHT)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image.getImage(), x, y, this); } } 

使用的图像:

AEROPLANERIGHTAEROPLANELEFT

在设置方向时,您也应该设置图像图标,或者设置getImageIcon(direction)

paintComponent中不应该发生重要的逻辑; 它应该尽可能快。 您没有(总)控制paintComponent调用的时间和频率。