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(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() — 建立桌面面板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)。