1

I have a main JFrame that calls a class(A) and that class calls another class (B)
In Class B I need a refrence to main JFrame
How to find that?

Thanks

Ariyan
  • 14,760
  • 31
  • 112
  • 175

3 Answers3

3

You can pass a reference of the JFrame to the classes like so

public class SomeFrame extends JFrame {
.
.
.
ClassA classA = new ClassA(arg1, arg2..., this, ...);
.
.
.

In ClassA:

 public class ClassA {
 private JFrame someFrame;
 public ClassA(arg1, arg2... JFrame someFrame,...)
 {
 this.someFrame = someFrame;
 .
 .
 . 
 ClassB classB = new ClassB(arg1, arg2, this.someFrame, ...);
 .
 .
 .

In ClassB:

public class ClassB {
private JFrame someFrame;

public ClassB(arg1, arg2, JFrame someFrame, ...) {
 this.someFrame = someFrame;
 .
 .
 .
npinti
  • 51,780
  • 5
  • 72
  • 96
2

Passing a reference seems like the best way.

Another method is to look up the current thread's stack trace and get it from there. It is one of the answers to this question: Java logger that automatically determines caller's class name

Community
  • 1
  • 1
Jon Onstott
  • 13,499
  • 16
  • 80
  • 133
1

You can use Inversion of Control (IoC) design pattern to avoid coupling your classes. A specific implementation of IoC is Dependency Injection. If you are using Java you can use Spring so you don't have to worry about the implementation of dependency injection.

In general terms there is a container that takes care of the references. In your case you can instruct the container to inject your main Frame to class B so the Frame will be accessible from class B.

Enrique
  • 9,920
  • 7
  • 47
  • 59