Search code examples
javamethodsjframejbuttonsubclassing

Cannot find symbol error when calling methods in an extended JButton class


I need some help resolving this issue. I can't seem to figure out why it wouldn't be working. I want to add more methods to my ButtonDefault class which is a subclass of JButton but I keep getting "symbol not found" error.

The code below, instantiation of the ButtonDefault worked, the default color and action of the button returned and work just fine. However all of that code is in the constructor of ButtonDefault. I want to add additional methods to the ButtonDefault class so later on I can change the color of the button and such.

the error that I keep getting:
MineSweeper.java:50: cannot find symbol symbol : method setUpButton() location: class javax.swing.JButton button[i][j].setUpButton();

I have 2 classes.

//MineSweeper.java
public class MineSweeper extends JFrame implements ActionListener,MouseListener,ItemListener {
    static JButton[][] button = new ButtonDefault[17][31];

    public void tileSetup()
    {
       button[i][j] = new ButtonDefault(i,j, this); //This work just fine
       //These work too - I just don't want it here. 
       //button[i][j].setIcon(null);
       //button[i][j].setBorder(UIManager.getBorder("Button.border"));
       //button[i][j].setBackground(null);
       //button[i][j].setBackground(Color.BLUE);
       //button[i][j].setBorder(new LineBorder(Color.GRAY, 1));
       //button[i][j].setEnabled(true);
       button[i][j].setUpButton(); //This don't work. 
    }
}

//ButtonDefault.java
public class ButtonDefault extends JButton implements ActionListener,MouseListener,ItemListener
{
    public ButtonDefault(){};
    public ButtonDefault(int x, int y, final MineSweeper mineObject)
    {
        this.setPreferredSize(new Dimension(18,18));
        this.setBackground(Color.BLUE);

        addMouseListener(new MouseListener() {  
           //All the code in here work just fine. 
    }

    public void setUpButton()
    {
        this.setIcon(null);
        this.setBorder(UIManager.getBorder("Button.border"));
        this.setBackground(null);
        this.setBackground(Color.BLUE);
        this.setBorder(new LineBorder(Color.GRAY, 1));
        this.setEnabled(true);
    }

}

Solution

  • setUpButton is a custom method of ButtonDefault not JButton. Therefore the array declaration should be

    private ButtonDefault[][] buttons = new ButtonDefault[ROWS][COLUMNS];
    

    Notes:

    • Generally using static declarations indicates poor design so use an instance field instead
    • Magic numbers are also perceived as poor design, consider at least using constants