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()时,它似乎以相同的方式工作。。。我应该保留它还是可以把它取下来?移除它的后果是什么?

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

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

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

当然,如果你想在其他地方重用这个JDialog(并且想做一些小的修改,比如位置和大小),我建议你把setTitle和(可能)setLocationRelativeTo方法移到调用框架中。

最新更新