Hello im trying to enable my JMenuItem from within an event listener but it seems to be out of scope. im new to java so how would i properly go about this. the said event listener will change to a new view and enable the disabled menu items.
//Create and add MenuItems
JMenuItem fileItem0 = new JMenuItem("Load");
collMenu.add(fileItem0);
JMenuItem fileItem1 = new JMenuItem("Add");
fileItem1.setEnabled(false);
collMenu.add(fileItem1);
JMenuItem fileItem2 = new JMenuItem("Delete");
fileItem2.setEnabled(false);
collMenu.add(fileItem2);
//Add Menu bar to frame
menubar.add(collMenu);
//Menu Item Functions
fileItem0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showMessageDialog(null,"You selected: Load.");
//Enable fileitem1 & 2 here ??
}
});
I hope this small example will help you clear your doubts...
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MenuExample extends JFrame {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenu menu1 = new JMenu("Edit");
JMenuItem item1 = new JMenuItem("New");
JMenuItem item2 = new JMenuItem("Open");
public MenuExample() {
setJMenuBar(menuBar);
setVisible(true);
setSize(400, 200);
menuBar.add(menu);
menuBar.add(menu1);
menu.add(item1);
menu.add(item2);
item1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
}
});
item2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
}
});
}
public static void main(String[] args) {
MenuExample ex = new MenuExample();
}
}