Jebathon
Jebathon

Reputation: 4581

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.

Upvotes: 0

Views: 434

Answers (2)

Ricardo Cacheira
Ricardo Cacheira

Reputation: 807

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.

Upvotes: 1

Ben
Ben

Reputation: 2057

In the main method, declare and initialize a Dialog - not a Window:

public class Main{

    Dialog instance = new Dialog();

    public Main(){    
        instance.methodWithinDialogClass();//add pictures/labels onto JDialog
    }
}

Your Dialog class should look like this:

public class Dialog{

    private Object pics;

    public Dialog(){
        //do some stuff to setup Dialog, initialize variable etc if you wish
    }

    public void methoWithinDialogClass(){
        //add pics etc to pics  
    }
}

I can't see what you need Window for - just declare and create a new Dialog in your main method, then you can access it.

Upvotes: 0

Related Questions