Frage

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);   

}

}

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top