Why is he doing two things?

I am writing a simple Jframe program with a menu and some options. Now, when I click on the open option, it does what the open action should do, but also does the close action. I do not know why. Here are the relevant 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 action 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);
         }
    }
}

      

+1


source to share


1 answer


if (e.getActionCommand().equalsIgnoreCase("Close")); // <--- remove this semi colon



This semi-column closes the if clause, making the code you think is if

always fire related , no matter which command.

+3


source







All Articles