使用单例模式设计一个多文档窗口(注:在Java AWT/Swing开发中可使用JDesktopPane和JInternalFrame来实现),要求在主窗体中某个内部子窗体只能实例化一次,即只能弹出一个相同的子窗体,如下图所示,编程实现该功能
类图:
实现代码:
客户端类Main: public class Main {
public static void main(String[] args) { System.out.println("Hello World!"); new JInternalFrameDemo(); } } 类JInternalFrameDemo : import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JDesktopPane; import javax.swing.JFrame;
public class JInternalFrameDemo extends JFrame implements ActionListener { private static JInternalFrame1 internalFrame; Container contentPane = this.getContentPane();
public JInternalFrameDemo() { super("主窗体"); contentPane.setLayout(new BorderLayout()); JButton button = new JButton("创建一个子窗体"); button.addActionListener(this); contentPane.add(button, BorderLayout.SOUTH); this.setSize(new Dimension(300, 300)); this.setVisible(true); this.addWindowListener(new WindowAdapter() { @Override
public void windowClosing(WindowEvent e) { System.exit(0); } }); }
public void actionPerformed(ActionEvent e) { internalFrame = JInternalFrame1.getJInternalFrame1("子窗体", true, true, true, true); internalFrame.setSize(new Dimension(200, 200)); internalFrame.setVisible(true); JDesktopPane desktopPane = new JDesktopPane(); contentPane.add(desktopPane); desktopPane.add(internalFrame); try { internalFrame.setSelected(true); } catch (java.beans.PropertyVetoException ex) { System.out.println("Exception while selecting"); } } } 类JInternalFrame1 : import javax.swing.JInternalFrame; public class JInternalFrame1 extends JInternalFrame { private static JInternalFrame1 JIF1 = null;
private JInternalFrame1(String name, boolean b1, boolean b2, boolean b3, boolean b4) { super(name, b1, b2, b3, b4); }
public static JInternalFrame1 getJInternalFrame1(String name, boolean b1, boolean b2, boolean b3, boolean b4) { if (JIF1 == null) JIF1 = new JInternalFrame1(name, b1, b2, b3, b4); return JIF1; }
} |