从另一个JFrames构造函数创建一个JFrame [英] Creating a JFrame from another JFrames constructor

查看:93
本文介绍了从另一个JFrames构造函数创建一个JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个扩展了JFrame的对象,我们称它们为FrameA FrameB FrameC.

I have 3 objects that extend JFrame let's call them FrameA FrameB FrameC.

FrameA是我的主应用程序窗口.如果未注册应用程序,请从FrameA的构造函数中创建FrameBFrameC.它们只是表明试用期的弹出窗口.

FrameA is my main application window. From FrameA's constructor if the application is not registered I create FrameB and FrameC. They are just popup's that indicate trial period.

10个应用程序中有2个冻结,并且从不显示B anc C帧,并且A帧无响应.

2 times out of 10 application freezes and never shows the B anc C frame and frame A becomes unresponsive.

我想知道以这种方式创建框架是否有副作用?

I was wondering if there is a side effect of creating frames in this fashion?

推荐答案

那是因为您没有让FrameA完成它的构造过程,而是要中断它,然后在同一线程中显示另外两个框架.

That's because you are not letting FrameA finish it's construction process, you're interrupting it and then in the same thread displaying those two other frames.

我建议您更改策略并使用工厂方法,并且可能与SwingUtilities.invokeLater方法结合使用.

I would suggest to change your strategy and use a factory method and probably in conjunction with SwingUtilities.invokeLater method.

假设您有类似的内容:

 public static void main( String [] args ) {
      JFrame a = new FrameA(); // Has both display logic and trial "pop up" logic
 }

更改为:

 public static void main( String [] args ) {
      JKFrame a = FrameA.createFrame(); // the same but splited like the following code 
 }


 class FrameA extends JFrame {
      // new method
      public static JFrame createFrame() {
            return new FrameA();  

      }
 }

什么都没有改变,您只是添加了工厂方法,以后您可以:

Nothing changed you just added the factory method, later you can:

         public static JFrame createFrame() {
            if( thatSpecialLogicSaysItIsTrialAndShouldPopUp() ) {
                  JFrame b = new FrameB();
                  b.setVisible( true );
                  JFrame c = new FrameC();
                  c.setVisible( true );
                  return new FrameA();

           } else {
            return new FrameA();
           }  

      }

您将在第二个代码中执行的操作是将逻辑与类构造函数分开,并将其放入工厂方法中.这样,如果 thatSpecialLogicSaysItIsTrialAndShouldPopUp 返回true,则显示B和C

What you will be doing in the second code is separate the logic from the class constructor and put it in the factory method. That way if thatSpecialLogicSaysItIsTrialAndShouldPopUp returns true, you display B and C

您也可以按照说明在此处使用JDialog,但是当您分开职责时,几乎所有问题都将消失.

You can also as described use a JDialog there, but pretty much the problems will be gone when you separate the responsabilities.

这篇关于从另一个JFrames构造函数创建一个JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆