Java制作MDI窗體源代碼

字號:

由于實際需要做一個MDI窗體,百度里面找到一個不錯的源代碼給大家分享一下。
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
     class JInternalFrame1 extends JFrame implements ActionListener{
     JDesktopPane desktopPane;
     int count = 1;
     public JInternalFrame1() {
     super("JInternalFrame1");
     Container contentPane = this.getContentPane();
     contentPane.setLayout(new BorderLayout());
     JButton b = new JButton("Create New Internal Frames");
     b.addActionListener(this);//當用戶按下按鈕時,將運行actionPerformed()中的程序
     contentPane.add(b, BorderLayout.SOUTH);
     /*建立一個新的JDesktopPane并加入于contentPane中
     */
     desktopPane = new JDesktopPane();
     contentPane.add(desktopPane);
     setSize(350, 350);
     show();
     addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
     System.exit(0);
     }
     });
     }
     /*產生一個可關閉、可改變大小、具有標題、可化與最小化的Internal Frame.
     */
     public void actionPerformed(ActionEvent e)
     {
     JInternalFrame internalFrame = new JInternalFrame(
     "Internal Frame "+(count++), true, true, true, true);
     internalFrame.setLocation( 20,20);
     internalFrame.setSize(200,200);
     internalFrame.setVisible(true);
     //取得JInternalFrame的Content Pane,用以加入新的組件。
     Container icontentPane = internalFrame.getContentPane();
     JTextArea textArea = new JTextArea();
     JButton b = new JButton("Internal Frame Button");
     /*將JTextArea與JButton對象加入JInternalFrame中。由此呆知,JInteranlFrame加入組件
     *的方式與JFrame是一模一樣。
     */
     icontentPane.add(textArea,"Center");
     icontentPane.add(b,"South");
     //將JInternalFrame加入JDesktopPane中,如此一來,即使產生很多JInternalFrame,JDesktopPane也
     //能將它們之間的關系管理得相當良好。
     desktopPane.add(internalFrame);
     try {
     internalFrame.setSelected(true);
     } catch (java.beans.PropertyVetoException ex) {
     System.out.println("Exception while selecting");
     }
     }
     public static void main(String[] args) {
     new JInternalFrame1();
     }
    }