简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM