Question

I'm working on a calculator that can run as JApplet and as application. When I run my code as application, the menubar shows up. But when i run it as a JApplet, it does not.

Is this a JApplet limitation? Because when i put all code (new JMenuBar, adding buttons, etc) in the calculator class it works. But using my own static method MenuBar.create(), which does the same thing and returns a JMenuBar, it doesnt work.

Here's the code, maybe i forgot something that makes the menubar not appear in the applet?

Calculator

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);
    }
}
Was it helpful?

Solution

I figured out the problem after experimenting for hours.

It seems that declaring a static JMenu/JMenuItem in a class like

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
}

was causing the menubar not to appear. After experimenting a bit, I found out that when running as a JApplet, JApplet runs void init() twice! After modifying my init method all my other code worked.

// I declared an boolean runOnce = false;
public void init() {
    if (runOnce) {
    new Calculator();
    }
runOnce = true
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top