[英]Switch imageIcon in java?
我有許多在窗口中移動的平面(線程),並且我想根據平面的方向切換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);
}
}
使用的圖像:
在設置方向時,您也應該設置圖像圖標,或者具有getImageIcon(direction)
。
在paintComponent中,不應發生繁瑣的邏輯; 它應該盡可能快。 您沒有(總計)控制何時以及多久調用一次paintComponent。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.