我应该将 Swing 组件声明为实例变量,还是只是从函数返回它们?
我刚刚开始使用 JAVA,我试图找出声明变量的最佳实践是什么,特别是在 GUI 组件方面。我试图使我的函数尽可能小,但我不确定是否应该将所有组件声明为 GUI 类的实例变量。
在这段代码中,我想只声明 gui 的主要部分,例如框架、面板、菜单栏和菜单本身,但我不确定应该将哪些部分声明为实例变量以及应该封装哪些部分。
class MyClass {
public JFrame frame;
public JPanel panel;
public JMenuBar menuBar;
public JMenu fileMenu;
public JMenu editMenu;
....
public void setUpEditMenu() {
editMenu = new JMenu("Edit");
editMenu.add(getEditMenuItem());
}
public JMenuItem getEditMenuItem() {
JMenuItem menuItem = new JMenuItem("Preferences");
return menuItem;
}
}
I am just getting started with JAVA and I am trying to figure out what the best practice for declaring variables would be, esp in regards to GUI components. I am trying to keep my functions as small as possible, but I am not sure if I should declare all my components as instance variables for my GUI class.
In this code, I was thinking to only declare major parts of the gui, such as the frame, panel, menuBar and the menus themselves, but I am not sure which parts I should be declaring as instance variables and what parts should be encapsulated.
class MyClass {
public JFrame frame;
public JPanel panel;
public JMenuBar menuBar;
public JMenu fileMenu;
public JMenu editMenu;
....
public void setUpEditMenu() {
editMenu = new JMenu("Edit");
editMenu.add(getEditMenuItem());
}
public JMenuItem getEditMenuItem() {
JMenuItem menuItem = new JMenuItem("Preferences");
return menuItem;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大多数 Java 的 GUI 构建器(如 Netbeans)将 GUI 组件声明为实例变量。
实际上没有必要封装它们,因为您最想访问它们已经封装的属性!
另外不要忘记过多函数调用的开销。
在我看来,不要过度封装东西。您的代码使用起来会更加复杂并且相当麻烦。
Most GUI Builders for Java (like Netbeans) declare GUI Components as instance variables.
There's actually no need to encapsulate them since you'll mostly want to access their already encapsulated properties!
Also don't forget about the overhead of excessive function calls.
In my opinion, don't over-encapsulate stuff. Your code will be much more complicated to use and rather cumbersome.