Reputation: 188
I am writing a simple Jframe program, with a menubar and some options. Now when I click on the option open it does what the open action should do, but it also does the close action. not sure why. Here are the respective codes.
//MenuItems
menuItem = new JMenuItem("New");
menuOptions.add(menuItem);
menuItem = new JMenuItem("Open");
menuOptions.add(menuItem);
menuItem.addActionListener(new Actions());
menuOptions.addSeparator();
menuItem = new JMenuItem("Save");
menuOptions.add(menuItem);
menuItem.addActionListener(new Actions());
menuOptions.addSeparator();
menuItem = new JMenuItem("Close");
menuOptions.add(menuItem);
menuItem.addActionListener(new Actions());
And the actions class:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
class Actions implements ActionListener
{
DisplayText dt;
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equalsIgnoreCase("Open"))
{
BasicFile f = new BasicFile();
// Important to encapsulate in try-catch block.
try{
dt = new DisplayText( f.getName(), f.getContents());
}catch(IOException ex){
ex.printStackTrace();//in case of exeption print to find error.
}
//Print to console for debuggin.
System.out.println(f.getName() ); //"The string that was clicked " + e.getActionCommand());
}
if(e.getActionCommand().equalsIgnoreCase("Close"));
{
dt = new DisplayText(00);
System.exit(0);
}
}
}
Upvotes: 1
Views: 94
Reputation: 2686
if (e.getActionCommand().equalsIgnoreCase("Close")); // <--- remove this semi colon
That semi colon closes the if clause, making the code you think is associated with the if
always fire, no matter what command.
Upvotes: 3