Search code examples
javajbuttonredundancy

how to use a class in multiple panels


i'm making a tank game. to avoid redundancy to make my buttons in the menupanel i wrote a class button:

package menu;

import java.awt.Image;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;

public class Button extends JButton{

    public JButton button;
    public ImageIcon buttonImage;

    public int x, width, height;

    public String backgroundPath;
    public int y;



    public Button(String backgroundPath,int x, int y, MenuPanel menuPanel)

    {
        super();
        this.backgroundPath = backgroundPath;
        this.x = x;
        this.y = y;

        buttonImage = new 
            ImageIcon(PlayPanel.class.getResource(backgroundPath));
        this.setIcon(buttonImage);
        this.setBounds(x, y, buttonImage.getIconWidth(), 
            buttonImage.getIconHeight());
        this.addActionListener(menuPanel);   
    }
}

in the constructor of the method i have MenuPanel menupanelbut i want to be able to use this code is multiple panels like the QuitPanel, HighScorePanel, ...etc.

i don't know which parameter i have to use for this so i'm stuck.

thanks in advance!!


Solution

  • Change the MenuPanel menuPanel parameter to ActionListener listener, since the only reason for it is to make it easier to attach an ActionListener to it, the button doesn't need to know about MenuPanel