简体   繁体   English

如何通过实例化类制作多个单独工作的 JButton?

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

I am just a beginner in java programming, and I got confused in class.我只是java编程的初学者,在课堂上我很困惑。 Our assignment was to make 3 jButtons, and when you click on them, a gif appears.我们的任务是制作 3 个 jButton,当你点击它们时,会出现一个 gif。 Our teacher said that we have to show the instantiation of 3 objects, each one controlling one button.我们老师说我们要展示3个对象的实例化,每个对象控制一个按钮。 Please help me;请帮我; I am so confused!我感到很困惑!

This is part of my code (the image Icon part)这是我的代码的一部分(图像图标部分)

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

^^ how do I make the code above so that fancyButton1 is linked with the instantiation of a class? ^^ 如何制作上面的代码,以便fancyButton1与类的实例化相关联? Sorry If what I'm saying doesn't make sense;对不起,如果我说的没有意义; I wasn't sure how to word it.我不知道该怎么说。

fancyButton1 = new ImageButton()

By calling new ImageButton() , you are instantiating a new object of the class ImageButton .通过调用new ImageButton() ,您正在实例化ImageButton类的一个新对象。

I am unsure quite what you are being asked to do.我不太确定你被要求做什么。 The following is code which instantiates three buttons:以下是实例化三个按钮的代码:

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

The other thing that you may be being asked to do, is to define the Cyberpet class so that it can create its own JButton, something along the following lines:您可能会被要求做的另一件事是定义 Cyber​​pet 类,以便它可以创建自己的 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);
}

Hope this helps.希望这可以帮助。 If I have misinterpreted the question then please let me know and I will try to provide a better answer.如果我误解了这个问题,请告诉我,我会尽力提供更好的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM