我有一个包含3个菜单的菜单栏。每个菜单都有一个菜单项。今天和关闭项目工作得很好,但xyz.txt项目不起作用。
当我点击xyz.txt项时,我得到以下异常:例外:
java.io.FileNotFoundException: xyz.txt (The system cannot find the file specified)
xyz.txt文件放在“AWT菜单”项目中,MenuDemo类放在AWT菜单/ src / awtmenu中。我试图将xyz.txt文件放在src或awtmenu包中,但问题仍然存在。
我应该在哪里放置xyz.txt文件?
任何反馈都会被贬低!
这是代码:
import java.awt.Color;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileReader;
import java.io.IOException;
public class MenuDemo extends Frame implements ActionListener
{
TextArea ta;
public MenuDemo()
{ // create menu bar
MenuBar mBar = new MenuBar();
setMenuBar(mBar); // add menu bar to frame
// create menus
Menu files = new Menu("Files");
Menu date = new Menu("Date");
Menu exit = new Menu("Exit");
ta = new TextArea(10, 40);
ta.setBackground(Color.cyan);
// add menus to menu bar
mBar.add(files);
mBar.add(date);
mBar.add(exit);
// create menu items to menus
MenuItem mi1 = new MenuItem("xyz.txt");
files.add(mi1);
date.add(new MenuItem("Today"));
exit.add(new MenuItem("Close"));
// linking listener
files.addActionListener(this);
date.addActionListener(this);
exit.addActionListener(this);
add(ta, "Center");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setTitle("Menu Practice");
setSize(400, 400);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();
if(str.equals("Close"))
{
System.exit(0);
}
else if(str.equals("Today"))
{
ta.setText("Today: " + new java.util.Date());
}
else
{
try
{
FileReader fr = new FileReader(str);
ta.setText("Folloiwing are file contents:\n\n");
int temp;
while( (temp = fr.read()) != -1)
{
char ch = (char) temp;
String s1 = String.valueOf(ch);
System.out.println(s1);
ta.append(s1);
}
fr.close();
}
catch(IOException e1)
{
ta.setText("Exception: " + e1);
}
}
}
public static void main(String args[])
{
new MenuDemo();
}
}