使用 Java Swing 创建 window

Creating a window with Java Swing

所以,我是Java语言的新手,所以我来学习JFrame class。 在很多教程中,我看到了这种创建新 JFrame 的方式window:

class Something extends JFrame{ 
  public static void main(String[] args) {
     new Something();
   }
  Something() {
   ... //Code here, the elements of the default JFrame window.
  }
}

所以我的问题是:我总是必须在 class 的构造函数中给出 JFrame window 的规范?难道没有别的办法吗?还是这种方式只是我不熟悉?另外,如果我想稍后在 main() 方法中更改创建的 JFrame,我的代码似乎有点混乱。 感谢您的回答!

您可以像配置任何对象一样配置 JFrame。如果您有对 JFrame 的引用,则可以调用它的 setter 和所有非私有方法。

您的问题涉及配置对象的最佳实践方法。我会寻找可以为您处理此问题的框架。总的来说,我认为任何重要的设置都应该在属性文件或系统属性(即不是代码)中进行外部配置,并且配置应该由与被配置的对象不同的对象完成。您希望您的配置集中,以便所有 windows 看起来相似等

作为该语言的初学者,您可以滚动一些小东西来为您做到这一点:

public interface WindowConfigurer {
    void configure(JFrame window);
}

public class DefaultWindowConfigurer implements WindowConfigurer {

    private Font font = // Default font

    public void configure(JFrame window) {
        window.setFont(font);
    }

    public void setFont(Font font) {
        this.font = font;
    }
}

public class EntryPoint {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Something something = new Something();
                WindowConfigurer windowConfigurer = new DefaultWindowConfigurer();
                windowConfigurer.configure(something);
                something.setVisible(true);
            }
        });
    }
}

public class Something extends JFrame {
    public Something() {
        // .. add buttons, controls, etc.
    }
}

接口 WindowConfigurer 设置了实现将 "configure" 给定 JFrame 的契约。您可以像我一样创建一个默认实现。抽象该配置的重要部分是您可能需要不同的配置,甚至可能想要在 运行 时间更改配置。例如,如果您的用户是老年人怎么办?您可能希望将字体更改为更大或使用高对比度颜色。因此,您可以创建一个名为 WindowConfigurerHighContrastWindowConfigurer 实现,它对 JFrame 执行任何必要的操作以使其易于阅读。这与 HTML 和 CSS 的关注点分离相同。您应该阅读 MVC 模式。

对于应用程序中的每个 JFrame,您只需 运行 configure() 即可获得与其他所有 JFrame 相同的样式 window。

我发现将 JPanel 子类化并在 main 中创建 JFrame 更方便:

public class MyClass extends JPanel {
  private JFrame frame;  // just so I have access to the main frame

  public MyClass( JFrame f ) {
     frame = f;
     // other things here
  }

  public void close() {
  // do things for closing
     int status = <something>;
     System.exit( status );
  }
   public static void main( final String[] args ) {
      SwingUtilities.invokeLater( new Runnable() {
         @Override
         public void run() {
            // Create and set up the window.
            final JFrame jf = new JFrame();
            jf.setName( "MyClass" );
            final MyClass item = new MyClass( jf);
            jf.add( item);
            jf.pack();
            jf.setVisible( true );
            jf.addWindowListener( new WindowAdapter() {
               @Override
               public void windowClosing( final WindowEvent arg0 ) {
                 item.close();
               }
            } );
         }
      } );
   }
}