如何在 Java 中组织 swing 内容(标签、按钮等)
我正在编写一个Java 程序,它是GUI(swing/awt 的东西)。用一种方法构建整个 GUI 是否明智?也就是说,创建并添加每个标签、按钮、菜单栏、菜单、菜单项等。
是否有更好的方法来组织这些?事件怎么样?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可能的话,最好将方法保留在几行代码中,并且永远不要超过一屏。如果您的 GUI 不仅仅是几个标签和一个按钮,您可能希望将其分解以提高可读性。有一个 createInputs() 方法、一个 createMenus() 方法、一个 createButtons() 方法等。
事件处理程序遵循类似的规则:如果它们是一两行代码,则使用匿名类,但其他任何内容都值得包含在其中它自己的类有一个名字。
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.
初始化 GUI 并不存在真正的“错误方式”;但是,根据我的经验,您可以将标签/按钮创建拆分为单独的方法以提高可读性。另外,如果您在单个面板或选项卡等中发现多个内容...那么您应该扩展 JPanel 并将所有内容放入您的构造函数中。组合 JPanel 还将帮助您更好地布局整个 GUI。
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.