0

My problem is that, this code is supposed to create a new button at the center when "Login" Menu is selected. When I select the menu, it prints "aaa" but does not add the button. How can I fix it? Thank you.

public class NewJApplet extends JApplet {
static JPanel panel;
static Container content;
static JMenuBar menubar;

/**
 * Initialization method that will be called after the applet is loaded into
 * the browser.
 */
public void init() {
    //panel = new JPanel();
    //BorderLayout borderlayout = new BorderLayout();
    //panel.setLayout(borderlayout);
    panel = new JPanel();
    BorderLayout borderlayout = new BorderLayout();
    panel.setLayout(borderlayout);


    menubar = new JMenuBar();
    JMenu login = new JMenu("Login");
    menubar.add(login);
    login.addMenuListener( new MenuListener(){
        public void menuSelected(MenuEvent e) {
            System.out.println("aaa");
            //menubar.setVisible(false);
            panel.add(new JButton("add"), BorderLayout.CENTER);               
        }
        public void menuCanceled(MenuEvent e) {

        }
        public void menuDeselected(MenuEvent e) {

        }
    });



    JMenu arizabildirimformu = new JMenu("Arıza Bildirim Formu");
    menubar.add(arizabildirimformu);

    setJMenuBar(menubar);


    //panel.add(new JButton("add"), BorderLayout.CENTER);
    //panel.add(menubar, BorderLayout.NORTH);
    // TODO start asynchronous download of heavy resources
    content = getContentPane();
    content.setLayout(new GridBagLayout()); 
    content.add(panel);   

}

}

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Try calling revalidate on the applet after you add the button. You might need to call repaint as well of that doesn't work – MadProgrammer Jun 13 '13 at 21:04
  • For many components in one space, use a [`CardLayout`](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html) as see in this [short example](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Jun 14 '13 at 06:38

1 Answers1

1

When you add a component to a visible GUI the code should be:

panel.add(...);
panel.revalidate();
panel.repaint(); // sometimes needed

I suggest you also look at How to Use Menus. You really should be using JMenuItems and ActionListeners.

camickr
  • 321,443
  • 19
  • 166
  • 288