Search code examples
javaswingmethodssuperclass

How can I access a method with several swing components from another class? (Java)


Suppose:

public class Window
{

public void Dialog ()
{
JDialog JD = new JDialog();

// add pictures/labels onto JDialog

}
}

And:

public class Main
{

//Suppose here is a GUI with a button that if clicked called the Dialog method

}

My issue is that I cannot figure out how to access the method on Eclipse. I created a constructor on the Window class to call the method but that didn't work for me.

 Window instance1 ; // create instance of class
   public Window (Window temp){
     instance1 = temp;      
}
///On Main Class

Dialog temp1 = new Dialog (temp1);

temp1.OpenDialog (); // calls method from other class

I know its a syntax issue with calling the constructor but I don't know whats wrong.


Solution

  • Try that:

    public class Window
    {
        public void dialog()// you re forgeting the parenttheses
        {
            JDialog JD = new JDialog();
    
            // add pictures/labels onto JDialog
        }
    }
    

    And you can access you method by:

    public class Main{
        Window win;
    
        public Main(){
            win = new Window();
            win.dialog();
        }
    }
    

    And another thing its a convention to not use uppercase letter on the first letter of method name. First letter in uppercase is used for class constructor.

    A contructor don't return any kind of variable and use the same name as Class.