温馨提示×

java jframe类如何实现多文档界面

小樊
85
2024-12-08 15:03:23
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,要实现多文档界面(Multiple Document Interface, MDI),可以使用JFrame作为主窗口,并在其中添加多个子窗口(通常称为文档)。以下是一个简单的示例,展示了如何使用JFrame实现MDI:

  1. 首先,导入所需的库:
import javax.swing.*;
import java.awt.*;
  1. 创建一个继承自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应用程序。你可以根据需要添加更多的子窗口,并根据实际需求为这些窗口添加更多功能和控件。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Java JFrame界面美化有哪些技巧

0