Search code examples
javaimageswingjbuttontextfield

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. Our assignment was to make 3 jButtons, and when you click on them, a gif appears. Our teacher said that we have to show the instantiation of 3 objects, each one controlling one button. 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? Sorry If what I'm saying doesn't make sense; I wasn't sure how to word it.


Solution

  • fancyButton1 = new ImageButton()
    

    By calling new ImageButton(), you are instantiating a new object of the class 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:

    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.