如何通过实例化 class 使多个 JButton 单独工作?

How do I make multiple JButtons that work individually through instantiating the class?

我只是 java 编程的初学者,我在 class 中感到困惑。我们的任务是制作 3 个 jButton,当您单击它们时,会出现一个 gif。我们老师说我们要展示3个对象的实例化,每个对象控制一个按钮。请帮我;我很困惑!

这是我的部分代码(图片图标部分)

public void addButtonsToContentPanel() {
    ImageIcon frog    = new ImageIcon("frog.gif");
    ImageIcon buffalo = new ImageIcon("buffalo.gif");

    fancyButton1      = new JButton("Fancy Button", frog);
    fancyButton1.setRolloverIcon(buffalo);


    p.add(fancyButton1);
    fancyButton1.addActionListener(this);
}

^^ 我如何编写上面的代码,以便 fancyButton1 与 class 的实例化相关联?对不起 如果我说的没有意义;我不知道怎么说。

fancyButton1 = new ImageButton()

通过调用 new ImageButton(),您正在实例化 class ImageButton 的新对象。

我不太确定你被要求做什么。以下是实例化三个按钮的代码:

ImageButton fancyButton1 = new ImageButton()
ImageButton fancyButton2 = new ImageButton()
ImageButton fancyButton3 = new ImageButton()

您可能被要求做的另一件事是定义 Cyber​​pet class 以便它可以创建自己的 JButton,大致如下:

class CyberPet {

    private String name;
    private ImageIcon imgIcon;
    private ImageIcon rolloverImgIcon;

    // Initialiser
    Cyberpet(String name, String pathToImgIcon, String pathToRolloverImgIcon) {
       this.name = name;
       this.imgIcon = new ImageIcon(pathToImgIcon);
       this.rolloverImgIcon = new ImageIcon(pathToRolloverImgIcon);
    }

    public JButton createButton() {
        JButton btn = new JButton(this.name, this.imgIcon);
        btn.setRolloverIcon(this.rolloverImgIcon);
    }
}    

public void addButtonsToContentPanel() {
    Cyberpet frog = new Cyberpet("frog.gif", "buffalo.gif");
    fancyButton1 = frog.createButton();
    fancyButton1.addActionListener(this);
}

希望这对您有所帮助。如果我误解了问题,请告诉我,我会尽力提供更好的答案。