2012-09-24 56 views
0

我在编程的Java桌面应用新的,所以我希望得到一些帮助...显示一个JFrame或JDialog的(摇摆)

我添加了建设者框架的组成部分。

当我在我的主框架的按钮点击,我显示的对话框是这样的:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
      BehaviorDialog behavDialog = new BehaviorDialog(this, rootPaneCheckingEnabled); 
      behavDialog.setVisible(true); 
    } 

而且我BehaviorDialog类是这样的:

public class BehaviorDialog extends javax.swing.JDialog { 

/** 
* Creates new form BehaviorDialog 
*/ 
public BehaviorDialog(java.awt.Frame parent, boolean modal) { 
    super(parent, modal); 
    initComponents(); 
    setTitle("Add behavior"); 
    setLocationRelativeTo(this); 
} 

/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 
//.... 
}// </editor-fold>       

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 

    /* Create and display the dialog */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
       BehaviorDialog dialog = new BehaviorDialog(new javax.swing.JFrame(), true); 
       dialog.addWindowListener(new java.awt.event.WindowAdapter() { 
        @Override 
        public void windowClosing(java.awt.event.WindowEvent e) { 
         System.exit(0); 
        } 
       }); 
       dialog.setVisible(true); 
      } 
     }); 
    } 
    // Variables declaration - do not modify      
    //... 
    // End of variables declaration     
} 

我的问题是:

  • 这是启动帧/对话框的正确方法吗? (它的工作原理,但我想,以确保它是否是最好的方式......)

  • 当我删除在maininvokeLater(),似乎相同的方式工作。我要好好保存或我可以删除它吗?删除它有什么后果?

在此先感谢!

+0

另请参阅此替代方法[方法](http://stackoverflow.com/a/2561540/230513)。 – trashgod

回答

3

这是可能的方法之一。有些人喜欢为每个对话框/窗口创建子类,所以该类正在管理自己的布局和(经常)行为。其他人更喜欢授权,即不要通过创建一种创建对话框及其布局的工厂方法为每个对话创建子类。我认为这种方法更好,因为它更灵活。您可以更轻松地将您的代码分层。例如创建主面板的图层,创建子面板的子图层,将面板放入对话框的高层等等。将来,您可以替换处理对话框的图层,并将相同的布局放入JFrame或其他面板等。

关于invokeLater() - 它只是异步运行你的代码。这对你的情况没有意义。但对于需要时间的操作是有用的。例如,如果您想要执行按钮上需要10秒钟的操作,则可能需要异步运行此操作。否则,您的GUI将冻结10秒。

+0

谢谢您的回答!但是,你能指出我关于授权方法的正确方向吗?如果你能告诉我一些例子/关于执行环节也将是巨大的......我已经搜查,但我没有发现任何东西非常有用... – amp

3

我不认为你的代码有什么问题。但是你一定要保持invokeLater,因为它可以为你处理线程。也就是说,它将这个事件排队,直到其他AWT事件结束。这使您确信界面保持平稳运行。

,如果你想重用此JDialog的其他地方(和想要做小的修改喜欢的位置和大小),当然不过,我建议你移动和的setTitle(可能)setLocationRelativeTo方法来调用框架。

+0

但是''setVisible(true)'方法不会被执行两次:1在我的主框架中,另一个在'invokeLater()'方法中?很抱歉,如果这个问题太明显了...... – amp

+0

好,如果你决定将它移到了invokeLater(),那么你只从构造函数中删除它:) – Rorchackh