I have a menu bar with 3 menus. Each menu has a menu item. Today and Close items are working very good, but the xyz.txt item is not working.
When I click the xyz.txt item I get this exception: Exception:
java.io.FileNotFoundException: xyz.txt (The system cannot find the file specified)
The xyz.txt file is placed in "AWT menu" project and the MenuDemo class is placed in AWT menu/src/awtmenu. I've tried to put the xyz.txt file in src or in awtmenu package but the problem persists.
Where should I place the xyz.txt file?
Any feedback will be apreciated!
This is the code:
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();
}
}