I'm writing a Java program which is GUI (swing/awt stuff). Is it 开发者_如何学运维sensible to build the entire GUI in one method? That is, create and add every label, button, menubar, menu, menu item, etc.
Is there a better way to organize this? What about the events?
Thanks!
It's best to keep methods to a few lines of code, if possible, and never more than one screen-full. If your GUI is anything more than a few labels and a button, you probably want to break it up for readability. Have one createInputs() method, one createMenus() method, one createButtons() method, etc.
Follow a similar rule for event handlers: use anonymous classes if they're one or two lines of code, but anything more deserves to be in its own class with a name.
There is no real "wrong way" to initialize a GUI; however, in my experience you can split up label/button creations into separate methods for readability. Also, if you find multiple things in a single panel or tab etc... then you should look to extend JPanel and put everything in your constructor there. Combining the JPanels will also help you to better layout the entire GUI.
精彩评论