Reputation: 580
I am having a JApplet
with a menu bar. The issue is whenever I click on the menu, no matter what the result is, it remains selected unless I click somewhere else on the screen.
Here is a small sample code to depict the scenario:
public class Frame extends JApplet{
public static String title = "Tower Defence Game";
JMenuBar menubar;
JMenu menuCreateMap;
@Override
public void init() {
menubar = new JMenuBar();
menuCreateMap = new JMenu("Create Map");
menuCreateMap.addMenuListener(new MenuHandler(new Frame()));
menubar.add(menuCreateMap);
setJMenuBar(menubar);
this.setPreferredSize(new Dimension(getHeight(), getWidth()));
setVisible(true);
}
}
The MenuHandler
class
public class MenuHandler extends Thread implements MenuListener {
Frame frame;
JMenu myMenu;
MenuHandler menuHandler;
MenuHandler() {}
MenuHandler(Frame frame) {
this.frame = frame;
menuHandler = new MenuHandler();
}
@Override
public void menuSelected(MenuEvent e) {
myMenu = (JMenu) e.getSource();
String selectedOption = myMenu.getText();
if(selectedOption.equalsIgnoreCase("Create Map")) {
menuHandler.start();
}
}
public void run() {
JLabel label = new JLabel("Hello World");
label.setText("Hello");
label.setBounds(100, 100, 100, 100);
this.frame.add(label);
}
}
This code would throw an exception but you would see that the Menu would stay selected.
How to fix this issue?
Upvotes: 1
Views: 657
Reputation: 580
If we want to trigger an event by the JMenu component in the JMenuBar, we should try changing it and adding JBUtton to the JMenuBar instead of JMenu. Because JMenu is not supposed to be used this way. Although, if you have a JMenuItem inside that JMenu, then you can trigger an event and handle it appropriately.
Upvotes: 2