我已经完全在 main 方法中初始化了我的 SWT shell,如下所示:
public class MySWTTemplate;
public static void main(String[] args){
Display display = new display();
Shell shell = new Shell(display);
shell.setSize(250, 250);
Rectangle bds = getMonitor().getBounds();
Point p = shell.getSize();
int xPos = (bds.width - p.x) / 2;
int yPos = (bds.height - p.y) / 2;
shell.setBounds(xPos, yPos, p.x, p.y);
shell.open();
while(!shell.isDisposed()){
if(!display.readAndDispatch()){
display.sleep();
}
}
display.dispose();
}
但我看到有些人设置它,以便 shell 启动和定义在他们自己的方法中,而启动时屏幕上的单元格定位在另一个方法中,并且两者都只是通过 main 方法调用。我对此进行了尝试并得出以下结论:
public class MySWTTemplate;
public static void main(String[] args){
Display display = new Display();
new MySWTTemplate(display);
display.didpose();
}
public MySWTTemplate(Display display){
Shell shell = new Shell(display);
shell.setSize(250, 250);
shellPos(shell);
shell.open();
while(!shell.isDisposed()){
if(!display.readAndDispatch()){
display.sleep()
}
}
}
public void shellPos(Shell shell){
Rectangle bds = shell.getMonitor().getBounds();
Point p = shell.getSize();
int xPos = (bds.width - p.x) / 2;
int yPos = (bds.height - p.y) / 2;
shell.setBounds(xPos, yPos, p.x, p.y);
}
两者都有效。我的两个问题是
1) 这样做只是为了视觉组织,还是为每个作业调用单独的方法会提供资源优势?
2)有人可以在第二个代码中解释当创建 MySWTTemplate() 方法然后在主方法中简单地使用“new MySWTTemplate(display)”调用时会发生什么吗?为什么方法的名称与类的名称完全相同?这从根本上说是什么(您不能将此方法设置为仅与任何其他方法名称一起公开。
最佳答案
这只是为了代码组织。当然,当它避免重复代码时会更有用(例如,因为您需要打开多个 shell 并以类似的方式放置它们)。
这不是方法,而是
MySWTTemplate
类的构造函数。如果您不知道什么是构造函数,您应该考虑阅读一本好的 Java 书籍或教程,因为您可能还会错过其他同样基本的内容。
关于java - SWT:更好地使用新的 display.shell 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056883/