Edu
Edu

Reputation: 13

Swing - Methods and attributes of an extended JPanel class inaccessible from JFrame

I am working on a project where I have a class called HGraphic that extends JPanel. This class has a public method called updateNum that receives an integer as a parameter and does some work with it, updating some elements.

This HGprahic class has an instance in the main class of my project (the main class extends JFrame)... I need to call this particular method of HGraphic from the main class sending a variable as parameter.

The problem is that although the method is declared as public I am not able to access to it doing the normal hGraphicInstance.method(variable) as I normally do.

I've gone through the JPanel documentation but have not found anywhere that says that you can not access custom methods... or that you can not create setters (another way of doing what I need).

When I instantiate the HGraphic class I use a JComponent class for doing it, could this be the reason?

Do you have any idea or advice? I would really appreciate a bit of light in this matter.. THANKS VERY MUCH!!!

I place the main bits of the code:

// CLASS CAUSING THE PROBLEM ------------------
public class HGraphic extends JPanel {

    // Attributes
    public int numberOfCoincidences = 0;

    // Constructor
    public HGraphic() {
        super(new BorderLayout());
    }

    public void updateNum(int tmpNum) {
        numberOfCoincidences = tmpNum;
    }
}

// MAIN FRAME CLASS ----------------------------------
public class HSFrame extends javax.swing.JFrame {

    private int newNum = 5;
    private JComponent newContentPane;

    public HSFrame() {
        initComponents();
    }

    private void initComponents() {
        newContentPane = new HGraphic();
        // HERE IS WHERE I WOULD LIKE TO ACCESS THE CLASS METHOD
        // NetBeans say it does not recognize this method :(
        newContentPane.updateNew(newNum);
    }
}

Thank you again!

Upvotes: 1

Views: 1917

Answers (1)

mhshams
mhshams

Reputation: 16962

because your instance (newContentPane) type is JComponent. you need to define it as HGraphic or cast it before method call.

private ***JComponent*** newContentPane;

needs to change to :

private HGraphic newContentPane;

or in your method call:

((HGraphic) newContentPane).updateNum(newNum);

Upvotes: 5

Related Questions