我正在编写一个简单的Jframe程序,带有菜单栏和一些选项。现在,当我点击选项open时,它会执行open操作应该执行的操作,但它也执行close操作。不知道为什么。以下是各自的代码。
//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());
动作类:
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);
}
}
}
答案 0 :(得分:3)
if (e.getActionCommand().equalsIgnoreCase("Close")); // <--- remove this semi colon
该半冒号关闭if子句,使得您认为与if
关联的代码始终触发,无论命令是什么。