This is intended as a sort of general question, but I'll give you my specific problem first:
I'm writing a GUI for my program at the moment for a program that will take the form of a frame with various widgets (labels, text fields etc.) placed on it. It's initially going to use the javax.swing
library, but I'm laving a layer of abstraction between the library and the GUI itself to make it easier to create a web application that does the same thing.
I'd like to have one class that represents the layout of the GUI: that is to say, it should contain all the information about where the various labels, buttons etc. are placed on the content pane. At the moment, the implementation I'm considering is the following:
class Layout
{
public MyLabel titleLabel;
public myTextField sequenceTextField;
[...]
public void drawTitleLabel()
{
titleLabel = new MyLabel("This is the title.");
titleLabel.setLocation(wherever);
titleLabel.draw();
}
public void drawSequenceTextField()
{
sequenceTextField = new MyTextField();
[...]
sequenceTextField.draw();
}
[...]
public void drawGuiFrame()
{
drawTitleLabel();
drawSequenceTextField();
[...]
}
}
So I declare each widget on the content pane as a field of the class Layout
, and then create methods drawWidgetName
that draw each widget. Lastly, I create a method that calls each of the draw...
methods in order to draw the whole GUI.
This seems wrong, though. The draw...
methods feel as if they should be methods of the individual widgets themselves, not of the larg-scale layout of the entire GUI. This suggests that I should create separate classes TitleLabel
, SequenceTextField
etc., each with a draw
method, and then just have a drawGuiFrame
method in the Layout
class that calls all of these draw
methods (I could even create an abstract class that these new classes could extend).
There would be a few other immediate advantages to this. Suppose I wanted to incorporate a system of checkboxes as well as my labels and text areas. Then I could declare that as its own class and give it properties isOptionA
, isOptionB
etc. to record which checkbox was ticked.
But I am slightly reluctant to implement the GUI this way, for two reasons. Firstly, creating so many new classes would clutter up the codebase with lots of small .java
files. Secondly, these would be very much 'single use' classes: I would never use the code again, since the classes would be designed purely for this particular GUI.
So - how many classes is too many? Is it OK to create lots of new classes that are only going to be used once just because you feel they should be classes? As I say, although I welcome advice specific to this particular problem, I'm also looking for more general pointers about when it's appropriate to add new classes.