Zvonko said:
Hi guys.
I have a question. Let us say that I write a MainForm class which has a
jDesktopPane, MenuBar and ToolBar. I would like to write classes for each
jInternalFrame and call it from MainForm using menu event listeners. But
when I try to access jDesktopPane from this outside class to add a
jInternaFrame, it says something about non static variable could not be
refernced from static ...
When learning Java I encountered this kind of error quite a lot. This
was probably because I was previously used to procedural languages more
than object-oriented languages. This led me to often create classes as
mere containers for static methods.
I found that these sort of problems were greatly reduced when I made a
serious effort to refactor my code so that I was instantiating objects
and then calling instance methods.
How do you update a component in another class?
I still consider myself a learner of Java so the following may be
completely off base, if so maybe someone more expert will jump in and
we'll both learn.
I'll assume you have something like:
class MainForm extends JFrame ...
...
class FooInternalFrame extends JInternalFrame ...
...
class BarInternalFrame extends JInternalFrame ...
Where possible, I try to avoid getting one class to directly update a
component in another class. I think it useful to have as clean a
separation as possible between classes.
Your MainForm could pass, to the JInternalFrame constructor, a reference
to the MainForm. The JInternalFrame could use this to invoke a method of
the MainForm. I've done this sort of thing but it doesn't feel quite right.
I've found defining and implementing Interfaces a useful way to control
this type of behaviour.
I wonder if it may be more Javaish for the MainForm to register a
"listener" in the JInternalFrame.
class MainForm extends JFrame implements XyzListener ...
public void XyzHappened() {
// update my component
}
...
FooInternalFrame jif = new FooInternalFrame();
jif.addXyzListener(this);
...
class FooInternalFrame extends JInternalFrame ...
public void addXyzListener(XyzListener baz) {
// add baz to list of listeners
}
...
// Something happened that needs
// MainFrame to update a component.
// Iterate over listeners
aListener.XyzHappened();