Having looked at a lot of code, I've found considerable variability in how things are done, especially putting GUI elements together. Here is a really simple case, but meant to represent the case where panel1 and panel2 actually have a lot of elements in them.
I have the option of putting all the commands in one constructor to build the whole thing, breaking the code up into methods to build the pieces, making multiple inner classes that construct the pieces or having each piece in their own class. I've implemented each possibility. Is any one of these 'best practice?' Or if depends on the situation, are there tips on when to use each of these constructs? I'm not real happy with the last case (separate classes) since the action listener is in one class and the panel is built in another. Did I extract out the panel correctly?
I think I am pretty close to forming a habit for how I do this, so I thought I'd ask the opinions of others before getting entrenched in a bad habit. It would help if there is some good reason to favor or disfavor any of these approaches if I knew the reason.
The simplest thing to do is build all the elements in one class.
However, in practice this can make classes with lots of lines of code in them. I've heard some rule of thumb that if the code won't fit on the screen, trying pulling some of it out into functions, which I can do as methods in
Java.
If I had a lot of code involved in making panel1 or panel2, that would at least make GUITest1 more readable. But I could also implement this with classes, which seems more 'Java-like.' Though I have no need to reuse these classes.
OK, so now that I have defined classes, I could move the class definitions to a separate file. I've not usually seen the ActionListener classes moved to their own file. In the above three implementations all the variables are known both to the constructor of the panel and the action listener, so I don't have to pass information around. Once the panel is in it's own class, it will need to let the main panel know who it's buttons are for the action listener. On the other hand, the file sizes become more manageable and I can write routines that just
test one class or another. So I may be going to far- but here is a fourth implementation.
Is this last bit right? It seems odd to extract out the bits to make the panel and then have to go to a lot of work to get those bits back so I can set up the action listeners in the main block. Should I have pulled them out as well. In that case, I would appear to need to set an argument as to who the other button is, so they could update what they need to.