使用Java Swing创建窗口

时间:2015-07-17 19:05:01

标签: java swing constructor jframe

所以,我是Java语言的新手,我开始研究JFrame类。 在很多教程中,我看到了这种创建新JFrame窗口的方法:

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

所以我的问题是:我总是要在我的类的构造函数中给出JFrame窗口的规范?还有另一种方式吗?或者这种方式只是我不熟悉?另外,如果我想稍后在main()方法中更改创建的JFrame,看起来我的代码有点无政府主义。 谢谢你的回答!

2 个答案:

答案 0 :(得分:3)

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

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

作为该语言的初学者,你可以为你做一些小事来做:

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设置一个合同,实现将“配置”给定的JFrame。您可以像我一样创建默认实现。抽象该配置的重要部分是您可能需要不同的配置,甚至可能希望在运行时更改配置。例如,如果您的用户是老年人怎么办?您可能希望将字体更改为更大或使用高对比度颜色。因此,您可以实现名为WindowConfigurer的{​​{1}}实现,该实现对JFrame执行任何必要的操作以使其易于阅读。这与HTML和CSS的关注点分离是一样的。你应该阅读MVC模式。

对于应用程序中的每个JFrame,您只需运行WindowConfigurerHighContrast即可获得与其他窗口相同样式的JFrame。

答案 1 :(得分:0)

我发现继承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();
               }
            } );
         }
      } );
   }
}