2013-07-20 17 views
0

我正在研究可以作为JApplet运行并作为应用程序使用的计算器。 当我将我的代码作为应用程序运行时,菜单栏显示出来。但是当我将它作为JApplet运行时,它不会。Java - JMenuBar没有显示在JApplet中,但它在作为应用程序运行时确实运行

这是JApplet限制吗?因为当我把所有的代码(新的JMenuBar,添加按钮等)在计算器类它的作品。但使用我自己的静态方法MenuBar.create(),它做同样的事情并返回一个JMenuBar,它不起作用。

这里的代码,也许我忘了一些东西,使菜单栏不出现在小程序中?

计算器

private void BuildGui() { 
//MenuBar.create() returns an JMenuBar filled with menus/items. 
    menuBar = MenuBar.create(); 
    panel.add(new JButton("test")); 
} 

private void Go() { 
// NOTE: this.isApplet works, it's a boolean i set during init() or main() 
    if (this.isApplet == true) { 
     setJMenuBar(menuBar); 
     setSize(500,600); 
     add(panel); 
    } else { 
     JFrame frame = new JFrame(); 
     frame.setJMenuBar(menuBar); 
     frame.getContentPane().add(BorderLayout.CENTER, panel); 
     frame.setSize(500,600); 
     frame.setVisible(true); 
    } 
} 
+1

为了更好地提供帮助,请发布[SSCCE](http://sscce.org/)。 –

+0

我找到了解决我的问题的方法,我会尽我所能发布答案。 (作为新用户,我必须等待8个小时)。 –

回答

0

我经历过了小时后想通了这个问题。

看来,在一个类中声明的静态JMenu的/ JMenuItem的像

public class MenuBar { 
private static JMenu[] menu = {new JMenu("Edit"), new JMenu("View") }; 

public static JMenuBar create() { 
    JMenuBar menuBar = new JMenuBar(); 
    for (JMenu m : menu) { 
     menuBar.add(m); 
    } 
    return menuBar 
} 

是导致不出现的菜单栏。经过一番试验后,我发现当作为JApplet运行时,JApplet会运行两次void init()。 修改我的init方法后,我所有的其他代码工作。

// I declared an boolean runOnce = false; 
public void init() { 
    if (runOnce) { 
    new Calculator(); 
    } 
runOnce = true 
} 
相关问题