tags:

views:

54

answers:

1

Hi,

After some advice on using jpanel - I'm new to java and playing around with the GUI elements.

Bascially what I'm curious about is if I can set up a Jpanel in one class, then somehow add labels etc to the that container, but from another class.

Is this possible ? or do i have to set the entire GUI up in one class, but then I guess I would have the same issue, if I wanted to update those fields I had set up in the main class from another class?

Apologies I don't really have any code that's usefull to demostrate here - I'm just trying to get the idea going, working out if its possible before I go ahead. And I'm not even sure if this is possible. Any advice would be greatly appreciated.

Thanks

+3  A: 

As long as you have a reference to the JPanel, you can add whatever GUI-element you want, by calling add(JComponent comp) on the JPanel.

So, you can do something like this:

class Panel extends JPanel{

    ...    

}

class Main{

    public Main(JPanel thePanel){
        thePanel.add(new JButton("Hello"));
    }
}

Was this what you were looking for?

You can also update the fields added to the panel from another class, if you have a public accessor-method set up, in the class. So in your panel class, you have a method:

public JButton getButton(){
    return button;
}

Then you can access the button from whatever class with a reference to your panel class, like this:

panel.getButton().setText("Some text");

Note that the button could just as well be public, then you could simply call the method directly: panel.button.setText("Some text"); but this is not considered good code, as it violates some general good OOP practices, not relevant to mention here.

Frederik Wordenskjold
Hi, I will give that a go - thanks
ivor