I know nothing about gui programming. I try to learn. I have simple question…
For example, I have small program. I have class that extends JFrame with main Window (MyWindowClass) and my “logic” class (MyClass) that do something (for example calculate something and I want to display it in window).
Should I implement this like:
class MyClass {
// ...
// ...
MyWindowClass window;
};
Or like this:
class MyWindowClass extends JFrame {
// ...
MyClass c;
};
I don’t know which class should be an owner and which class should be have main method…
Please help me…
I try to write in Java (Swing) but this is general question I guess.
3
Between your two options having the view know about your “logic” class would be the better method. This would allow you to create or modify your view without having to change your logic classes. If you put your view inside of your “logic” classes it dramatically limits your flexibility.
As people mentioned in the comments read up on the MVC pattern as that will demonstrate some ideal solutions.
Classical Model-View-Controller question.
MyClass
is a model. It has the domain data and implements domain logic.
SWING components (JTextField
, JTable
) are a view. They know how to show data to the user and how to accept user input, but know nothing about your domain model.
MyWindowClass
is a controller. It needs to mediate your model and view – e.g. set text field value to object property value or update object in response to button press.
Hence, MyWindowClass
needs to be able to access both the model and the view. There is little reason for MyClass
to know about the UI – e.g. you may use the same domain class in different UI (e.g. list of objects and edit form for a single object).
Ideally, wouldn’t have either your logic class or your window class contain the other, but would instead use a “application” object to contain them both.
However, if for some reason that isn’t practical, the choice of which object contains the other when both objects are from entirely different areas of concern should be determined by which object is dependent upon the other. If MyWindowClass
will never run without a MyClass
object, it may contain such as a member; if MyClass
will never run without MyWindowClass
, it may contain such instead.
(Although this should only be a concern when the overall application design doesn’t allow for proper separation, which is an instance that occurs less and less frequently as languages and frameworks have evolved from the bad old days.)
As an aside, if you are forced into cross-concern composition, make sure that you keep the references as generic as practicable. You want to be able to substitute a MyModifiedClass
for MyClass
in MyWindowClass
with a minimuim of fuss down the road.