I am trying to build a simple notepad. But for some reason my action event is not being triggered after clicking on the New menu item. The code given below should call a newFile() method, when user click on New menu item.
public class MainUi implements ActionListener{
//all the variables
public JFrame window;
public JTextArea textArea;
public JScrollPane scrollPane;
public JMenuBar menuBar;
public JMenu menuFile, menuEdit, menuFormat;
public JMenuItem fNew, fOpen, fSave, fSaveAs, fExit;
//creating instance of all the functional class
File_functions file = new File_functions(this);
//Constructor to build the ui
public MainUi() {
createWindow();
createMenuBar();
addFileMenu();
createTextArea();
window.setVisible(true);
}
public static void main(String[] args) {
new MainUi();
}
//menu bar
public void createMenuBar() {
menuBar = new JMenuBar();
window.setJMenuBar(menuBar);
//add file to the menu
menuFile = new JMenu("File");
menuBar.add(menuFile);
}
//all the file menu
public void addFileMenu() {
fNew = new JMenuItem("New");
menuFile.add(fNew);
menuFile.addActionListener(this);
menuFile.setActionCommand("New");
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String command = e.getActionCommand();
System.out.print(command);
switch (command) {
case "New": file.newFile(); break;
}
}
}
There is no error showing in console neither inside another class (File_function).
fNew = new JMenuItem("New");
menuFile.add(fNew);
menuFile.addActionListener(this);
The ActionListener needs to be added to the JMenuItem:
fNew = new JMenuItem("New");
menuFile.add(fNew);
//menuFile.addActionListener(this);
fNew.addActionListener(this);
Note, there is no need to set the action command. It will default to the text of the menu item.