You can do this with inheritance or using an interface where the variable is set as a constant in the parent class. Since you are extending JLabel, you must implement an interface for both classes:
public interface MyInterface { int someint = 9; } public class MyClass1 extends JLabel implements MyInterface {
Edit
Since you want to be able to change the same variable from different classes, you need to make sure that you do not change copies and change the same variable, so you should use the volatile
keyword for the java variable, so that all threads must check the value before its updates.
Now you need to have a separate class so that instances can be made from other classes to get the value. You must use the static
to ensure that one copy is stored for all instances of the class.
public class MyVariableWrapper { public static volatile int some_var = 9; public void updateSomeVar(int newvar) { some_var = newvar; } public int getSomeVar() { return some_var; } }
Now two other classes just do it:
public class MyClass1 extends JLabel { MyVariableWrapper myVariableWrapper; MyClass1() { super(); myVariableWrapper = new MyVariableWrapper();
Now you can do this:
MyClass2 myClass2 = new MyClass2(); System.out.println(""+myClass2.getSomeVar());
source share