Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding a new JMenu to an existing JMenuBar

 
Lars Tode
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've a JMenuBar with File,Option, View, Help i.e.
When the user is changing something the JMenuBar had to add sometime a new JMenu, for instance a JMenu called Extras.
I tried it this way:
myWindow.getJMenuBar().add(myJMenu);
but it doesn't work
Does anyone know a way how i can add or remove JMenu's to/from the JMenuBar while the application is running?
regards
Lars
 
Rajendar Goud
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
u can add the run time menus. u can go thru this example,which adds a new Menu when a button is clicked..
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class runtimemenu extends JFrame implements ActionListener
{
Container contentPane;
JMenuBar mb;
JMenu file,edit;
JMenuItem open,cut;
JButton addButton;
runtimemenu()
{
contentPane = getContentPane();
file = new JMenu("File");
edit = new JMenu("Edit");
open = new JMenuItem ("open");
cut = new JMenuItem ("cut");
file.add(open);
mb = new JMenuBar();
mb.add(file);
setJMenuBar(mb);
addButton = new JButton("Add a menu");
contentPane.add(addButton);
addButton.addActionListener(this);
contentPane.setLayout(new FlowLayout());
setSize(300,250);
setVisible(true);

}

public void actionPerformed(ActionEvent e)
{
edit.add(cut);
mb.add(edit);
setJMenuBar(mb);
validate();
}

public static void main(String a[])
{
new runtimemenu();
}
}
cheers,
Raj
 
Rajendar Goud
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I missed out the second part of the question.
u can remove the menus directly the same way as u added.
the below code consists of an extra button 'remove'.
if(e.getSource().equals(addButton))
{
edit.add(cut);
mb.add(edit);
setJMenuBar(mb);
validate();
}
else if(e.getSource().equals(remove))
{
mb.remove(edit);
setJMenuBar(mb);
validate();
}
}

cheers,
Raj
 
Lars Tode
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
thanks for ur help
I dint really make an instance of the class JMenu. I've written a method that returns a JMenu. So i'd to work with no variables. Is there a way to do it without mb.add(edit); ??
greetx
Lars
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic