Search code examples
javaswinggraphicsjframepaintcomponent

How to pass paintComponent and object with the logic needed to draw something?


So I have instantiated an object with a 2D matrix of data associated with this object. I perform all my logic on this matrix of data and now I am ready to see a visual of this 2D matrix.

I want to print either a solid rectangle of void rectangle depending on the value in the matrix.

Here is my trouble in pseudo-code:

public void paintComponent(Graphics g)
{
    g.setColor(Color.gray);
    g.fillRect(0,0, 500, 500);

    // I need the logic from the instantiated logic from the main method but I cant pass the object into the paintComponent method when I tried. How can I access the objectGrid object from the main method in this method? 

}

public static void main(String[] args) {
    Class newObject = new Class();

    //Do operations on newly instantiated object
    newObject.performOperation;

    // Start a new JFrame object which will call the paintComponent method automatically
    // But I want to pass newObject to paintComponent method and I don't know how to do it

    JFrame window = new JFrame();
    window.setSize(500, 500);
    window.setVisible(true);
}

I hope this makes sense. Thanks


Solution

  • You need to have a new class which extends JFrame

    public class MyClass{
        //...
    }
    
    public class MyFrame extends JFrame{
        private MyClass obj;
    
        public MyFrame(MyClass obj){
            this.obj = obj;
            //...
        }
    
        //...
    
        public void paintComponent(Graphics g){
            // Paint obj in here
        }
    
    }
    

    Then, you can use like that:

    MyClass obj = new MyClass();
    MyFrame frame = new MyFrame(obj);
    //...
    frame.setVisible(true);