【问题标题】:SWT: better to use methods for new display.shell?SWT:更好地使用新的 display.shell 方法?
【发布时间】:2014-02-27 00:56:49
【问题描述】:

我一直在 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() 方法然后在 main 方法中简单地用“new MySWTTemplate(display)”调用时发生了什么吗?为什么方法的名称与类的名称完全相同?这从根本上说的是什么(您不能将此方法设置为 public 与任何其他方法名称。

【问题讨论】:

    标签: java shell methods swt


    【解决方案1】:
    1. 这只是为了代码组织。当然,它在避免重复代码时更有用(例如,因为您需要打开多个 shell 并以类似的方式定位它们)。

    2. 这不是方法,而是MySWTTemplate 类的构造函数。如果你不知道构造函数是什么,你应该考虑阅读一本好的 Java 书籍或教程,因为你可能也会错过其他同样基本的东西。

    【讨论】:

    • 谢谢...并且会做的。我记得构造函数,我会刷新自己。同时你能解释一下为什么'public MySWTTemplate (Display display)' 不是一种方法而'public void shellPos(Shell shell)' 是一种方法吗?除非我在调用 shellPos 方法时错了。另外,'public static void main(String[] args) 被认为是正确的方法吗?
    • 构造函数与类同名,没有返回类型(用new调用)。方法有一个返回类型(voidshellPos 的情况下)。 main 是一种方法,是的。更准确地说是一个静态方法(它属于整个类而不是这个类的对象)。
    • 所以 static 指定一个方法可以在类范围内使用。而将修饰符完全排除在外则只能由类中的特定对象访问?
    • 它可以被任何对象访问(因为它是public)。但它只能在这个类的特定对象上调用。 IE。如果你在某个地方有MySWTTemplate template = ...;,你可以打电话给template.shellPos(...)
    猜你喜欢
    • 1970-01-01
    • 2011-02-07
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 2012-09-11
    相关资源
    最近更新 更多