2016-12-05 38 views
0
package database; 

import javax.swing.JFrame; 
import javax.swing.JMenu; 
import javax.swing.SwingUtilities; 

public class Application { 
    public static void main(String[] args) { 

     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       JFrame frame = new ApplicationFrame("Application"); 
       frame.setSize(500, 400); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setVisible(true); 
      } 
     }); 

    } 

    public class ApplicationFrame extends JFrame { 

     private CompaniesPanel companiesPanel; 

     public ApplicationFrame(String title) { 
      super(title); 

      setLayout(new BorderLayout()); 

      JMenuBar menuBar = new MenuBar("Menu"); 

      Container container = getContentPane(); 
      container.add(menuBar, BorderLayout.NORTH); 

     } 
    } 

    public class MenuBar extends JMenuBar { 

     public MenuBar(String title) { 
      super(); 

      JMenu menuFile = new JMenu("File"); 
      add(menuFile); 

      JMenu menuOpen = new JMenu("Open"); 
      menuFile.add(menuOpen); 

      JMenuItem menuItemCompanies = new JMenuItem("Companies"); 
      menuOpen.add(menuItemCompanies); 

      menuItemCompanies.addActionListener(new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent arg0) { 
        // In here I would like to take a CompaniesPanel and insert 
        // it into 
        // an ApplicationFrame if the Companies button is pressed on 
        // menu 
       } 

      }); 
     } 
    } 

    public class CompaniesPanel extends JPanel { 
     public CompaniesPanel() { 
      Dimension size = getPreferredSize(); 
      size.width = 250; 
      setPreferredSize(size); 

      setBorder(BorderFactory.createTitledBorder("Company Names")); 

      setLayout(new GridBagLayout()); 

      GridBagConstraints gridBagConstraints = new GridBagConstraints(); 

     } 
    } 
} 

我只想让我的应用程序打开该菜单,剩下的就是空白,当从下拉菜单中按下公司时打开公司面板。这可能没有打开另一个jFrame?如何使用ActionListener在JFrame内插入JPanel?

+0

是的。不知道它是否与你使用类的方式一致。我只会制作1个gui文件和1个启动文件,启动gui。那么您可以轻松访问gui类中的框架并向其添加新的jpanel – XtremeBaumer

+1

考虑一个CardLayout面板;它将其组件视为一堆或“卡片”组合;当显示一个时,其余的部分隐藏在显示的“下面”。您可以使用一张没有任何内容的卡,然后在选择正确的菜单选项时切换到您想要的任何一张。 – arcy

回答

1
container.add(menuBar, BorderLayout.NORTH); 

首先,并非如何将菜单添加到框架。一个框架有一个为菜单栏保留的特殊区域。

相反,你只需使用:

setJMenuBar(menuBar); 

阅读从How to Use Menus Swing的教程部分获取更多信息和工作的例子。

正如已经提到的CardLayout将是一个不错的选择。通过添加两个面板(一个为空,另一个为公司),布局的首选尺寸将由您的公司面板确定,以便在显示公司面板时框架尺寸不会更改。

Swing教程还提供了一个关于How so Use CardLayout的部分,其中包含一些工作示例以帮助您入门。

保留所有Swing基础知识的Swing教程的参考。