我有一些图片,我需要改变点击,现在只有三个图像的每个类别,3个鼻子,3个眼睛和3个嘴巴。所以我采取这种方法来解决我的问题,但是我意识到这不是最好的方式去解决它,因为图像的数量是硬编码,我希望它改变dinamically。我需要一些想法或建议。动作侦听器,点击更改图像。
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
/**
* Create the panel.
*/
private int nose = 1;
private int mouth = 1;
private int eyes = 1;
Color[] color ={Color.BLUE, Color.RED, Color.PINK,Color.CYAN,Color.WHITE};
static int colorCounter =1 ;
public ImagePanel() {
}
public void changeNose(){
nose = ++nose % 3;
nose++;
}
public void changeMouth(){
mouth = ++mouth % 3;
mouth++;
}
public void changeEyes(){
eyes = ++ eyes % 3;
eyes++;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.green);
g.setColor(color[colorCounter]);
g.fillOval(40, 120, 400, 400);
ImageIcon hat = new ImageIcon
(ImagePanel.class.getResource("/a06Face/Images/santa.png"));
hat.paintIcon(this, g, 160, 3);
ImageIcon eyes1 = new ImageIcon
(ImagePanel.class.getResource("/a06Face/Images/eyes"+eyes+".png"));
eyes1.paintIcon(this, g,180, 200);
ImageIcon nose1 = new ImageIcon(ImagePanel.class.getResource("/a06Face/Images/nose"+nose+".png"));
nose1.paintIcon(this, g, 180, 300);
ImageIcon mouth1 = new ImageIcon
(ImagePanel.class.getResource("/a06Face/Images/mouth"+mouth+".png"));
mouth1.paintIcon(this, g, 170, 400);
repaint();
}
}
你能解释一下你的问题吗?我不清楚你打算怎么做? 3鼻子,嘴巴等是什么意思? –
我有三个不同的名为nose1,nose2,nose3的png文件。我想每次点击时切换它们,所以我已经使用模运算符来保持图像数量超过3,因此我不会超出范围。但正如你可以看到我的变化眼睛,改变嘴巴,改变鼻子硬编码与3图像工作。我想实现一个不同的方式来做到这一点,我注意到,如果我想添加另一个图像,我必须更改字段值和方法值。 – mrKapplan