繁体   English   中英

显示一个JFrame或JDialog(Swing)

[英]Display a JFrame or JDialog (Swing)

我是Java桌面应用程序编程的新手,所以希望获得一些帮助...

我在构建器中添加了框架的组件。

当单击主框架的按钮时,将显示如下对话框:

    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                   
}

我的问题是:

  • 这是开始帧/对话框的正确方法吗? (它有效,但是我想确定这是否是最好的方法...)

  • 当我删除main中的invokeLater()时,它似乎以相同的方式工作...应该保留它还是可以删除它? 删除它会有什么后果?

提前致谢!

我认为您的代码没有任何问题。 但是您绝对应该保留invokeLater,因为它会为您处理线程。 也就是说,它将对该事件进行排队,直到其他AWT事件结束。 这样可以确保界面保持平稳运行。

但是,当然,如果您想在其他地方重用此JDialog(并希望做一些小的修改,例如位置和大小),我建议您将setTitle和(可能)setLocationRelativeTo方法移至调用框架。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM