Java 如何在jdialog中添加内部框架

Java 如何在jdialog中添加内部框架,java,Java,我正在使用以下代码: JDialog d=new JDialog(); JInternalFrame i=new JInternalFrame("HI",false,false,false,false); i.setPreferredSize(new Dimension(100,100)); d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); d.setTitle("Wait

我正在使用以下代码:

      JDialog d=new JDialog();
         JInternalFrame i=new JInternalFrame("HI",false,false,false,false);
       i.setPreferredSize(new Dimension(100,100));
     d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
     d.setTitle("Wait dialog");
    d.add(i);
     d.pack();
      d.setPreferredSize(new Dimension(100,100));
        d.setLocation(300,300);
    d.setAlwaysOnTop(true);
   d.setVisible(true);
但是我得到的不是大小为100*100的jdialog,而是一个默认宽度和高度的小窗口,为什么会发生这种情况? 注意:我对JFrame做了同样的操作,得到了结果。但是我希望它出现在JDialog上

提前感谢

您需要在JDialog中添加所有组件之后,但在使用setVisible(true)显示之前,在JDialog上调用pack()

另一方面,最好通过一个JDialog构造函数重载将JDialog与其父窗口(可能是JFrame)关联起来

编辑:您不希望将JinternalFrame直接添加到JDialog或其他顶级窗口。而是创建一个JDesktopPane,设置其preferredSize,将其添加到JDialog的contentPane中,然后将JInternalFrame添加到JDesktopPane中

编辑2:您还需要设置内部框架的大小和位置(setBounds可以很好地用于此),并在内部框架上调用setVisible(true)。关于使用内部框架和桌面窗格的Swing教程将告诉您所有这些

编辑3:例如

class testDialog {

   public static void main(String[] args) {
      JDialog d = new JDialog();
      JDesktopPane desktoppane = new JDesktopPane(); // added
      desktoppane.setPreferredSize(new Dimension(100, 100));// added
      JInternalFrame i = new JInternalFrame("HI", false, false, false, false);
      // i.setPreferredSize(new Dimension(100, 100));
      i.setBounds(0, 0, 100, 100);// added
      desktoppane.add(i);
      i.setVisible(true);

      d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
      d.setTitle("Wait dialog");
      // d.add(i);
      d.add(desktoppane); // added
      d.pack();
      // d.setPreferredSize(new Dimension(100, 100));
      d.setLocation(300, 300);
      d.setAlwaysOnTop(true);
      d.setVisible(true);
   }
}
这是SSCCE:

   import java.awt.Dimension;
   import javax.swing.*;

   public class testDialog
  {

public static void main(String []args)
   {
     JDialog d=new JDialog();
    JInternalFrame i=new JInternalFrame("HI",false,false,false,false);
    i.setPreferredSize(new Dimension(100,100));
    d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
      d.setTitle("Wait dialog");
   d.add(i);
    d.pack();
   d.setPreferredSize(new Dimension(100,100));
    d.setLocation(300,300);
     d.setAlwaysOnTop(true);
    d.setVisible(true);
      }
      }

我现在这么做了。但是它没有帮助。然后我建议你创建并发布一个非常小的可编译、可运行的演示程序,一个显示问题的程序。此过程称为创建SSCCE。有关如何做到最好的更多信息,请查看此链接:请参阅我对以上答案的第一次编辑。很抱歉没有提前推荐。同样,请参阅上面对我答案的编辑。如果要使用JInternalFrames,需要使用JDesktopPane。