在Java中,要实现多文档界面(Multiple Document Interface, MDI),可以使用JFrame作为主窗口,并在其中添加多个子窗口(通常称为文档)。以下是一个简单的示例,展示了如何使用JFrame实现MDI:
import javax.swing.*;
import java.awt.*;
JFrame
的类,例如MDIFrame
:public class MDIFrame extends JFrame {
public MDIFrame() {
setTitle("MDI Frame");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建一个菜单条
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem closeItem = new JMenuItem("Close");
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(closeItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// 添加一个名为"Document 1"的子窗口
JInternalFrame document1 = new JInternalFrame("Document 1");
document1.setSize(400, 300);
document1.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
add(document1);
// 添加一个名为"Document 2"的子窗口
JInternalFrame document2 = new JInternalFrame("Document 2");
document2.setSize(400, 300);
document2.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
add(document2);
// 显示主窗口
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MDIFrame frame = new MDIFrame();
});
}
}
在这个示例中,我们创建了一个名为MDIFrame
的类,它继承自JFrame
。我们在构造函数中设置了主窗口的标题、大小、关闭操作和位置。然后,我们创建了一个菜单栏,并向其中添加了“文件”菜单和其中的“新建”、“打开”和“关闭”菜单项。
接下来,我们创建了两个名为“Document 1”和“Document 2”的子窗口,并将它们添加到主窗口中。最后,我们使用setVisible(true)
方法显示主窗口。
运行这个程序,你将看到一个包含两个子窗口的MDI应用程序。你可以根据需要添加更多的子窗口,并根据实际需求为这些窗口添加更多功能和控件。