Search code examples
javauser-interfaceswingorganizationcode-organization

How to organize swing stuff in Java (labels, buttons, anything)


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!


Solution

  • 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.