Skip to content
Advertisement

Passing variable from JFrame to JPanel?

Now i’ve spent about an hour searching the web for a solution and I either see solutions that seem too complex for me or No solution at all. I’m a student so I’m fairly new to coding so excuse my lack of knowledge on the subject. But this issue has been bugging me for way longer than I feel like it should.

After searching i settled upon the idea of placing a method inside the JFrame that just returns said variable.

Then in the JPanel I would just call this method and assign it to a variable. Then use that variable to draw the oval. This however doesn’t work or more so i think it’s not receiving a value because eclipse shows no issues. I try placing the getter method calls where the “x’s” would be but nothing. Though when put constants in those spots like “50” it prints a circle.

Am I going about this right?? How can I pass a value from the Jframe to the Jpanel?

Code:

JavaScript

jframe:

JavaScript

jpanel:

JavaScript

edit day 2-the get method(in circMain):

JavaScript

then I place this is circRan:

JavaScript

still not.. Welp assignment is due by the end of today feel like the solution is something simple I’m missing as it usually is.. and its aggravating.

Advertisement

Answer

The line

JavaScript

is equivalent to

JavaScript

i.e. your class variable circRan.x will get the return value of calling the function getX() declared for class circRan, which is declared for JComponent, a superclass of JPanel.

What you want to achieve is calling the function declared for instances of circMain (which btw overrides the getX() which is declared by JFrames superclass Component). For this you’d need the instance of circMain you want this value of.

Alternatively, if all instances of circMain share this value (or if only one instance will exist) you can declare x,xfinal and getX() static. Then you can call circMain.getX(), calling the static function directly on the class rather than an instance. Depends on your use case, though.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement