动作侦听器,单击时更改图像

  • 本文关键字:图像 单击 侦听器 java
  • 更新时间 :
  • 英文 :


我有一些我需要在单击时进行更改的图像,现在每个类别的图像只有三个图像,3个鼻子,3眼和3张嘴。因此,我采用了这种方法来解决我的解决方案,但是我意识到这不是最好的方法,因为图像的数量很难编码,我希望它可以在dinam上更改。我需要一些想法或建议。

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();
    }
}  

您可以使用Mouselistener。如何做到这一点:

//in your Class constructor
public XYZ()
{
.....
Timer t = new Timer(0,new Listener());
t.start();
addMouseListener(new Mouse());
// later in program
private class Mouse extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
<object>.doMethod(e.<otherMethod>);
}
}

这只是如何使用通用的鼠标。修改它以适合您的程序。

好吧,让我们尝试一下。让我们定义一个实例字段,该字段将所有图像项保存在我们的系统中。这可能是

private List<ImageIcon> imgIcons = new ArrayList<ImageIcon>;

然后编写一种将图像图标添加到此列表中的方法。看起来像这样。

private void addImageIcon(ImageIcon imgIcon){
    this.imgIcons.add(imgIcon);
}

从您需要添加图像的任何地方调用此方法。然后,当您需要计算此面板中的图像数时,您可以获取数组的大小。希望这可以帮助。快乐编码!

最新更新