2014-03-06 36 views
0

我有一个JFrame JF菜单栏,当我点击菜单栏项目时,一个新的JFrame JF1被创建并显示出来,但是当我点击JF1的关闭按钮时,两个JFrame都关闭了。当我在JF1的关闭按钮点击,我只想JF1被关闭,没有JFJMenuBar到JFrame

JMenuBar menubar; 
JMenu help; 
JMenuItem about; 

public GUI() { 
    setLayout(new FlowLayout()); 

    menubar = new JMenuBar(); 
    add(menubar); 

    help = new JMenu("Help"); 
    menubar.add(help); 
}` 

回答

1

我推荐你使用DesktopPane和JInternalFrame。

要对主框架进行更改:contentPane(JPanel)将为JDesktopPane。

它显示的JFrame点击将是一个JInternalFrame。

在JMenuItem的ActionListener的,你会做到这一点:

MyInternalFrame internalFrame = new MyInternalFrame(); 
internalFrame.show(); 
contentPane.add(internalFrame); 

MyInternalFrame是类显示Frame(扩展的JInternalFrame类)的。

要关闭“internalFrame”,只需在布局中添加一个按钮,使文本“退出”,并在您的actionListener中添加“dispose()”。

尝试它,知道它的工作原理;)

- 编辑--- 主类(JFrame中)

public class Main extends JFrame { 

private JDesktopPane contentPane; 
private JMenuBar menuBar; 
private JMenu mnExample; 
private JMenuItem mntmAbout; 

public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       Main frame = new Main(); 
       frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

public Main() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(20, 20, 800, 800); 

    menuBar = new JMenuBar(); 
    setJMenuBar(menuBar); 

    mnExample = new JMenu("Help"); 
    menuBar.add(mnExample); 

    mntmAbout = new JMenuItem("About"); 
    mntmAbout.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      About frame = new About(); 
      frame.show(); 
      contentPane.add(frame); 
     } 
    }); 
    mnExample.add(mntmAbout); 
    contentPane = new JDesktopPane(); 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
    setContentPane(contentPane); 
    contentPane.setLayout(null); 
} 
} 

关于类(JInternalFrame的)

public class About extends JInternalFrame { 

public About() { 
    setBounds(100, 100, 544, 372); 

    JLabel lblSomeText = new JLabel("Some Text"); 
    getContentPane().add(lblSomeText, BorderLayout.CENTER); 

    JButton btnClose = new JButton("Close"); 
    btnClose.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      dispose(); 
     } 
    }); 
    getContentPane().add(btnClose, BorderLayout.SOUTH); 

} 

} 
+0

你的意思是把JInternalFrame添加到JF rame? – user3275944

+0

到desktopPane和JFrame里面的desktopPane,就像cintentPane –

+0

看到答案,我会把代码放在那里 –