Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java create menu in another class, add to frame

I try to create a menu in Another class and add it to my frame, but it does not work (nothing adds). Can you help me see what is wrong with the code, thank you.

Class Test:

public class Test extends JFrame {

    public Test() {                
        MenuBar menuBar = new MenuBar();                
        setJMenuBar(menuBar);            
        pack();
        setVisible(true);
    }
 }

Class Menu:

public class MenuBar extends JMenuBar {

    JMenuBar menuBar;
    JMenu menu;

    public MenuBar() {
        menuBar = new JMenuBar();
        menu = new JMenu("File");
        menuBar.add(menu);            
        MenuItem menuItem = new MenuItem();
        menu.add(menuItem);   
    }
}

class MenuItem:

public class MenuItem extends JMenuItem {

    JMenuItem menuItemUndo;
    JMenuItem menuItemRedo;

    public MenuItem() {
        menuItemUndo = new JMenuItem("Undo");
        menuItemRedo = new JMenuItem("Redo");
    }    
 }
like image 794
user2939293 Avatar asked Nov 28 '25 23:11

user2939293


1 Answers

MenuBar extends JMenuBar and because of that you don't have to create a new JMenuBar inside its constructor. This make more sense:

public class MenuBar extends JMenuBar {

    JMenu menu;

    public MenuBar() {
        menu = new JMenu("File");
        this.add(menu);            
        .....
    }
}

The same thing applies for the MenuItem class.

public class Undo extends JMenuItem {

    public MenuItem() {
        this.setText("Undo");
    }    
}
like image 67
Titus Avatar answered Nov 30 '25 12:11

Titus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!