首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Swing 筆記:JInternalFrame 與 JDesktopPane 實作多文檔介面 (MDI)

     編輯:Java 程式設計入門

Swing 提供 JInternalFrame 與 JDesktopPane 實現多文檔介面(MDI),讓視窗能在主視窗內自由移動、最大化、最小化、關閉。本文整理類別繼承結構、建構子參數與實際範例。

類別繼承結構

java.lang.Object
 --java.awt.Component
 --java.awt.Container
 --javax.swing.JComponent
 --javax.swing.JInternalFrame
java.lang.Object
 --java.awt.Component
 --java.awt.Container
 --javax.swing.JComponent
 --javax.swing.JLayeredPane
 --javax.swing.JDesktopPane

JInternalFrame 是輕量級元件,必須放入 JDesktopPane(或其他 RootPaneContainer)才能顯示。

JInternalFrame 常用建構子

  • JInternalFrame() — 無標題、不可縮放、關閉、最大化/最小化
  • JInternalFrame(String title) — 有標題,其餘同上
  • JInternalFrame(String title, boolean resizable) — 可縮放
  • JInternalFrame(String title, boolean resizable, boolean closable) — 可關閉
  • JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) — 可最大化
  • JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) — 完整功能

JDesktopPane 建構子

  • JDesktopPane() — 建立桌面面板

完整範例:動態建立內部視窗

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

public class JInternalFrameDemo extends JFrame implements ActionListener {
    JDesktopPane desktopPane;
    int count = 1;

    public JInternalFrameDemo() {
        super("JInternalFrame Demo");
        Container cp = getContentPane();
        cp.setLayout(new BorderLayout());

        JButton btn = new JButton("Create New Internal Frame");
        btn.addActionListener(this);
        cp.add(btn, BorderLayout.SOUTH);

        desktopPane = new JDesktopPane();
        cp.add(desktopPane, BorderLayout.CENTER);

        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        JInternalFrame iframe = new JInternalFrame(
            "Internal Frame " + count++, true, true, true, true);
        iframe.setLocation(20 * count, 20 * count);
        iframe.setSize(300, 200);
        iframe.setVisible(true);

        Container icp = iframe.getContentPane();
        icp.add(new JTextArea(), BorderLayout.CENTER);
        icp.add(new JButton("Internal Button"), BorderLayout.SOUTH);

        desktopPane.add(iframe);
        try { iframe.setSelected(true); } catch (java.beans.PropertyVetoException ex) {}
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(JInternalFrameDemo::new);
    }
}

重點:

  • 內部視窗加入 JDesktopPane 後,桌面面板會自動管理層級關係。
  • 元件加入內部視窗方式與 JFrame 相同,透過 getContentPane()。
  • 可透過 setSelected(true) 將視窗置頂(需捕捉 PropertyVetoException)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved