11 Replies - 2089 Views - Last Post: 22 April 2011 - 08:49 PM Rate Topic: -----

#1 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Creating a Java Notepad with file I/O and menus

Posted 19 April 2011 - 10:00 PM

I have to create a Notepad application that has Menus, reads data from a text file, and saves data to a text file

I have implemented the menus, but I am having trouble implementing the Open menu item and Save so that the Open/Save dialog box appears.


Here's what I've done so far (with no errors):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;


public class NotepadIO extends JFrame
{
private final Color[] colorValues =
{Color.BLACK, Color.BLUE, Color.RED, Color.GREEN};
private JRadioButtonMenuItem[] colorItems; // color menu items
private JRadioButtonMenuItem[] fonts; // font menu items
private JCheckBoxMenuItem[] styleItems; // font style menu items
private JLabel displayJLabel; // displays sample text
private ButtonGroup colorButtonGroup;
private int style;
private JTextArea textPanel = new JTextArea();

public NotepadIO()
{
super("Notepad");
setSize(600,600);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(textPanel, BorderLayout.CENTER);

// create File menu
JMenu fileMenu = new JMenu("File");

JMenuItem newItem = new JMenuItem("New"); // create New menu item
fileMenu.add( newItem ); // add new item to file menu
JMenuItem openItem = new JMenuItem("Open..."); // create Open... menu item
fileMenu.add( openItem ); // add open item to file menu

openItem.addActionListener
/**************************************************************************
* PURPOSE: To exit Notepad when the user clicks "Exit" from the
* File menu
*
* PRECONDITIONS: The Notepad is opened
*
* POSTCONDITIONS: The Notepad will close once the user clicks "Exit"
*
* ALGORITHM: Click "Exit"
* Exit the program
**************************************************************************/
(
new ActionListener() // anonymous inner class
{
// terminate application when user clicks exitItem
public void actionPerformed(ActionEvent aEvent)
{

}
} // end anonymous inner class
); // end call to addActionListener

JMenuItem saveItem = new JMenuItem("Save"); // create Save menu item
fileMenu.add( saveItem ); // add save item to file menu
JMenuItem saveAsItem = new JMenuItem("Save As..."); // create Save As... menu item
fileMenu.add( saveAsItem ); // add save as item to file menu
JMenuItem exitItem = new JMenuItem("Exit"); // create Exit menu item
fileMenu.add( exitItem ); // add exit item to file menu




exitItem.addActionListener
/**************************************************************************
* PURPOSE: To exit Notepad when the user clicks "Exit" from the
* File menu
*
* PRECONDITIONS: The Notepad is opened
*
* POSTCONDITIONS: The Notepad will close once the user clicks "Exit"
*
* ALGORITHM: Click "Exit"
* Exit the program
**************************************************************************/
(
new ActionListener() // anonymous inner class
{
// terminate application when user clicks exitItem
public void actionPerformed(ActionEvent aEvent)
{
System.exit(0);
}
} // end anonymous inner class
); // end call to addActionListener

JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(fileMenu);

JMenu helpMenu = new JMenu("Help"); // create the help menu
JMenuItem aboutItem = new JMenuItem("About..."); // create About menu item
helpMenu.add(aboutItem); // add about item to file menu
bar.add(helpMenu); // add help menu to menu bar

// if About is clicked, implement the action listener for it
aboutItem.addActionListener(
/**************************************************************************
* PURPOSE: To create a dialog box showing the name of the software
* version and creator
*
* PRECONDITIONS: The user has clicked "About..." on the Help menu.
* The action listener has been implemented for the help
* menu
*
* OUTPUT: The dialog box will show on the screen with the following
* text:
*
* NetBeans IDE
* Version 6.9.1
* Matthew Rivera
*
* POSTCONDITIONS: The dialog box will exit once the user clicks "OK" on it
*
* ALGORITHM: Show dialog box
* Close dialog box when user clicks "OK"
**************************************************************************/

new ActionListener() // anonymous inner class
{
// display message dialog when user selects About...
public void actionPerformed( ActionEvent event )
{
// shows the messageDialog on the screen
JOptionPane.showMessageDialog( NotepadIO.this,
"NetBeans IDE\nVersion 6.9.1\nMatthew Rivera",
"About", JOptionPane.PLAIN_MESSAGE );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener for the About item

// create the Format menu
JMenu formatMenu = new JMenu("Format");

// array listing string colors
String[] colors = { "Black", "Blue", "Red", "Green" };

JMenu colorMenu = new JMenu( "Color" ); // create color menu
colorMenu.setMnemonic( 'C' ); // set mnemonic to C

// create radio button menu items for colors
colorItems = new JRadioButtonMenuItem[ colors.length ];
colorButtonGroup = new ButtonGroup(); // manages colors
ItemHandler itemHandler = new ItemHandler(); // handler for colors

// create color radio button menu items
for ( int count = 0; count < colors.length; count++ )
{
colorItems[ count ] =
new JRadioButtonMenuItem( colors[ count ] ); // create item
colorMenu.add( colorItems[ count ] ); // add item to color menu
colorButtonGroup.add( colorItems[ count ] ); // add to group
colorItems[ count ].addActionListener( itemHandler );
} // end for

colorItems[ 0 ].setSelected( true ); // select first Color item

formatMenu.add( colorMenu ); // add color menu to format menu
formatMenu.addSeparator(); // add separator in menu

JMenu fontMenu = new JMenu( "Font" ); // create font menu
String[] styleNames = { "Bold", "Italic" }; // names of styles
styleItems = new JCheckBoxMenuItem[ styleNames.length ];
StyleHandler styleHandler = new StyleHandler(); // style handler

// create style checkbox menu items
for ( int count = 0; count < styleNames.length; count++ )
{
styleItems[ count ] =
new JCheckBoxMenuItem( styleNames[ count ] ); // for style
fontMenu.add( styleItems[ count ] ); // add to font menu
styleItems[ count ].addItemListener( styleHandler ); // handler
} // end for

formatMenu.add( fontMenu ); // add Font menu to Format menu
bar.add( formatMenu ); // add Format menu to menu bar
} // end MenuFrame constructor

// inner class to handle action events from menu items
private class ItemHandler implements ActionListener
{
// process color and font selections
public void actionPerformed( ActionEvent event )
{
// process color selection
for ( int count = 0; count < colorItems.length; count++ )
{
if ( colorItems[ count ].isSelected() )
{
displayJLabel.setForeground( colorValues[ count ] );
break;
} // end if
} // end for
repaint(); // redraw application
} // end method actionPerformed
} // end class ItemHandler

// inner class to handle item events from checkbox menu items
private class StyleHandler implements ItemListener
{
// process font style selections
public void itemStateChanged( ItemEvent e )
{
String name = displayJLabel.getFont().getName(); // current Font
Font font; // new font based on user selections

// determine which CheckBoxes are checked and create Font
if ( styleItems[ 0 ].isSelected() &&
styleItems[ 1 ].isSelected() )
font = new Font( name, Font.BOLD + Font.ITALIC, 10 );
else if ( styleItems[ 0 ].isSelected() )
font = new Font( name, Font.BOLD, 10 );
else if ( styleItems[ 1 ].isSelected() )
font = new Font( name, Font.ITALIC, 10 );
else
font = new Font( name, Font.PLAIN, 10 );

displayJLabel.setFont( font );
repaint(); // redraw application
} // end method itemStateChanged
} // end class StyleHandler
}
/***************************************************************************/


I've tried using this code for my NotepadIO.java file

view source
01	public void actionPerformed (ActionEvent e) {
02	        // if the source of the event was our "close" option
03	        if (e.getSource() == this.close)
04	            this.dispose(); // dispose all resources and close the application
05	         
06	        // if the source was the "open" option
07	        else if (e.getSource() == this.openFile) {
08	            JFileChooser open = new JFileChooser(); // open up a file chooser (a dialog for the user to browse files to open)
09	            int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel)
10	            // NOTE: because we are OPENing a file, we call showOpenDialog~
11	            // if the user clicked OK, we have "APPROVE_OPTION"
12	            // so we want to open the file
13	            if (option == JFileChooser.APPROVE_OPTION) {
14	                this.textArea.setText(""); // clear the TextArea before applying the file contents
15	                try {
16	                    // create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
17	                    Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
18	                    while (scan.hasNext()) // while there's still something to read
19	                        this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
20	                } catch (Exception ex) { // catch any exceptions, and...
21	                    // ...write to the debug console
22	                    System.out.println(ex.getMessage());
23	                }
24	            }
25	        }
26	         
27	        // and lastly, if the source of the event was the "save" option
28	        else if (e.getSource() == this.saveAsFile) {
29	            JFileChooser save = new JFileChooser(); // again, open a file chooser
30	            int option = save.showSaveDialog(this); // similar to the open file, only this time we call
31	            // showSaveDialog instead of showOpenDialog
32	            // if the user clicked OK (and not cancel)
33	            if (option == JFileChooser.APPROVE_OPTION) {
34	                try {
35	                    // create a buffered writer to write to a file
36	                    BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
37	                    out.write(this.textArea.getText()); // write the contents of the TextArea to the file
38	                    out.close(); // close the file stream
39	                } catch (Exception ex) { // again, catch any exceptions and...
40	                    // ...write to the debug console
41	                    System.out.println(ex.getMessage());
42	                }
43	            }
44	        }
45	    }



in my but I get errors in my program. I've also included the following java file from my textbook in my project

// Fig. 17.21: FileDemonstration.java
// Demonstrating JFileChooser.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class FileDemonstration extends JFrame
{
   private JTextArea outputArea; // used for output
   private JScrollPane scrollPane; // used to provide scrolling to output
   
   // set up GUI
   public FileDemonstration()
   {
      super( "Testing class File" );

      outputArea = new JTextArea();

      // add outputArea to scrollPane
      scrollPane = new JScrollPane( outputArea ); 

      add( scrollPane, BorderLayout.CENTER ); // add scrollPane to GUI

      setSize( 400, 400 ); // set GUI size
      setVisible( true ); // display GUI

      analyzePath(); // create and analyze File object
   } // end FileDemonstration constructor

   // allow user to specify file or directory name
   private File getFileOrDirectory()
   {
      // display file dialog, so user can choose file or directory to open
      JFileChooser fileChooser = new JFileChooser();
      fileChooser.setFileSelectionMode(
         JFileChooser.FILES_AND_DIRECTORIES );

      int result = fileChooser.showOpenDialog( this );

      // if user clicked Cancel button on dialog, return
      if ( result == JFileChooser.CANCEL_OPTION )
         System.exit( 1 );

      File fileName = fileChooser.getSelectedFile(); // get File

      // display error if invalid
      if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
      {
         JOptionPane.showMessageDialog( this, "Invalid Name",
            "Invalid Name", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 );
      } // end if

      return fileName;
   } // end method getFile

   // display information about file or directory user specifies
   public void analyzePath()
   {
      // create File object based on user input
      File name = getFileOrDirectory();

      if ( name.exists() ) // if name exists, output information about it
      {
         // display file (or directory) information
         outputArea.setText( String.format(
            "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s",
            name.getName(), " exists",
            ( name.isFile() ? "is a file" : "is not a file" ),
            ( name.isDirectory() ? "is a directory" : 
               "is not a directory" ),
            ( name.isAbsolute() ? "is absolute path" : 
               "is not absolute path" ), "Last modified: ",
            name.lastModified(), "Length: ", name.length(), 
            "Path: ", name.getPath(), "Absolute path: ",
            name.getAbsolutePath(), "Parent: ", name.getParent() ) );

         if ( name.isDirectory() ) // output directory listing
         {
            String[] directory = name.list();
            outputArea.append( "\n\nDirectory contents:\n" );
   
            for ( String directoryName : directory )
               outputArea.append( directoryName + "\n" );
         } // end else
      } // end outer if
      else // not file or directory, output error message
      {
         JOptionPane.showMessageDialog( this, name +
            " does not exist.", "ERROR", JOptionPane.ERROR_MESSAGE );
      } // end else  
   } // end method analyzePath
} // end class FileDemonstration



but all this does is create a window showing info about whether the opened text file is a file or is a directory, file location, etc. It doesn't print the text to the Notepad text area. The JFileChooser should be used in order for the user to get the file name for my program. Can someone help me here?

Is This A Good Question/Topic? 0
  • +

Replies To: Creating a Java Notepad with file I/O and menus

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10574
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Creating a Java Notepad with file I/O and menus

Posted 19 April 2011 - 10:02 PM

You get errors. Let's start there. What are they? Please post them exactly as they appear on your compiler.
Was This Post Helpful? 0
  • +
  • -

#3 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: Creating a Java Notepad with file I/O and menus

Posted 19 April 2011 - 10:20 PM

Here are my errors:

E:\Adv Java\WritePad\src\WritePad.java:379: illegal start of type
BasicAction() //default constructor
E:\Adv Java\WritePad\src\WritePad.java:379: ';' expected
BasicAction() //default constructor
E:\Adv Java\WritePad\src\WritePad.java:379: illegal start of type
BasicAction() //default constructor
E:\Adv Java\WritePad\src\WritePad.java:379: <identifier> expected
BasicAction() //default constructor
E:\Adv Java\WritePad\src\WritePad.java:379: ';' expected
BasicAction() //default constructor
E:\Adv Java\WritePad\src\WritePad.java:379: invalid method declaration; return type required
BasicAction() //default constructor
E:\Adv Java\WritePad\src\WritePad.java:379: ';' expected
BasicAction() //default constructor
7 errors




View Postmacosxnerd101, on 19 April 2011 - 10:02 PM, said:

You get errors. Let's start there. What are they? Please post them exactly as they appear on your compiler.

Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10574
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Creating a Java Notepad with file I/O and menus

Posted 19 April 2011 - 10:23 PM

Where is your WritePad class? That is where you are getting all the errors.

Also, please properly indent your code in the future to make it more readable.
Was This Post Helpful? 0
  • +
  • -

#5 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: Creating a Java Notepad with file I/O and menus

Posted 19 April 2011 - 10:27 PM

View Postmacosxnerd101, on 19 April 2011 - 10:23 PM, said:

Where is your WritePad class? That is where you are getting all the errors.

Also, please properly indent your code in the future to make it more readable.


Oops, my bad. I used the wrong java file. Here are the errors for my NotepadIO.java file

E:\Adv Java\NotepadIOTest\src\NotepadIO.java:132: cannot find symbol
symbol: variable close
if (e.getSource() == this.close)
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:133: cannot find symbol
symbol: method dispose()
this.dispose(); // dispose all resources and close the application
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:136: cannot find symbol
symbol: variable openFile
else if (e.getSource() == this.openFile) {
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:138: showOpenDialog(java.awt.Component) in javax.swing.JFileChooser cannot be applied to (<anonymous java.awt.event.ActionListener>)
int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel)
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:143: cannot find symbol
symbol: variable textArea
this.textArea.setText(""); // clear the TextArea before applying the file contents
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:148: cannot find symbol
symbol: variable textArea
this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:157: cannot find symbol
symbol: variable saveAsFile
else if (e.getSource() == this.saveAsFile) {
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:159: showSaveDialog(java.awt.Component) in javax.swing.JFileChooser cannot be applied to (<anonymous java.awt.event.ActionListener>)
int option = save.showSaveDialog(this); // similar to the open file, only this time we call
^
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:166: cannot find symbol
symbol: variable textArea
out.write(this.textArea.getText()); // write the contents of the TextArea to the file
^
9 errors
E:\Adv Java\NotepadIOTest\nbproject\build-impl.xml:528: The following error occurred while executing this line:
E:\Adv Java\NotepadIOTest\nbproject\build-impl.xml:261: Compile failed; see the compiler error output for details.
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10574
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Creating a Java Notepad with file I/O and menus

Posted 19 April 2011 - 10:57 PM

You don't have variables for any of the ones causing the Cannot Find Symbol errors.

Quote

E:\Adv Java\NotepadIOTest\src\NotepadIO.java:133: cannot find symbol
symbol: method dispose()
this.dispose(); // dispose all resources and close the application

In the given context, this refers to your ActionListener, not the JFrame. If you remove this from your dispose() invocation, it will invoke the dispose() method for the encapsulating Object- your JFrame.

Same thing applies here:

Quote

E:\Adv Java\NotepadIOTest\src\NotepadIO.java:138: showOpenDialog(java.awt.Component) in javax.swing.JFileChooser cannot be applied to (<anonymous java.awt.event.ActionListener>)
int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel)

Was This Post Helpful? 0
  • +
  • -

#7 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: Creating a Java Notepad with file I/O and menus

Posted 21 April 2011 - 08:41 PM

Here is my updated code along with some links:
/******************************************************************************
 * PROGRAMMER:      Matt Rivera
 * 
 * COURSE:          CSCI 3234.04
 * 
 * ASSIGNMENT:      Program #3
 * 
 * DATE:            April 26, 2011
 * 
 * ENVIRONMENT:     NetBeans IDE 6.9.1 running on Windows XP 32-bit
 * 
 * FILES INCLUDED:  A screenshot of the output from this program are on a file
 *                  named "Program 3 Output.docx"
 * 
 * PURPOSE:         Develop a Notepad-like application that includes menus, 
 *                  features of reading data from a text file and saving data to 
 *                  a text file. 
 * 
 * INPUT:           none
 * 
 * PRECONDITIONS:   The Notepad application will include the following menus: 
 *                  File, Format, and Help .
 *                  
 *                  The File menu will include the following menu items: 
 *                  New, Open..., Save, Save As..., and Exit.
 *                  The Format menu will include a Font and Color menu item. 
 *                      The Font menu item includes a submenu with these items Bold, Italic.
 *                          The Font submenu items extended from this menu item will use check boxes                                          
 *                      The Color menu item includes a submenu with these items: Black, Blue, Red, Green
 *                          The Color submenu items extended from this menu item will use radio buttons
 *                  The Help menu will include the following menu Item: About... 
 *                  
 * POSTCONDITIONS:  When the Open menu item is clicked, the Open dialog box that
 *                  appears in a real Notepad app will appear on the screen.
 *                  The text from the document chosen will appear in the text area
 *                  if the user clicks "OK".
 *                  When the Save As... menu item is clicked, the Save dialog box 
 *                  that appears in a real Notepad app will appear on the screen
 *                  When the About is clicked, the name of the software, version of the software,
 *                  and the name of the developer will be displayed on a dialog box.
 * 
 * ALGORITHM:       If the user chooses File----> Open
 *                      choose file to Open
 *                  If the user chooses File----> Save
 *                      choose location to save the file
 *                  If the user chooses File----> Exit
 *                      exit the Notepad
 *                  If the user chooses Format--->Color and then clicks a color radio
 *                      button, place a dot inside the circle next to it and remove
 *                      it from its previous location
 *                  If the user chooses Format--->Font and then clicks a check box,
 *                      place a checkmark inside the circle next to it and remove
 *                      it if the user clicks the checked menu item
 *                  If the user chooses Help----> About
 *                      Display dialog box
 *
 *******************************************************************************/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;


public class NotepadIO extends JFrame 
{
    private final Color[] colorValues =
        {Color.BLACK, Color.BLUE, Color.RED, Color.GREEN};
    private JRadioButtonMenuItem[] colorItems; // color menu items
    private JRadioButtonMenuItem[] fonts; // font menu items
    private JCheckBoxMenuItem[] styleItems; // font style menu items
    private JLabel displayJLabel; // displays sample text
    private ButtonGroup colorButtonGroup;
    private int style;
    private JTextArea textPanel = new JTextArea();
    
    public NotepadIO()
    {
        super("Notepad");
        setSize(600,600);
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(textPanel, BorderLayout.CENTER);
        this.textPanel.setEditable(true);
        // create File menu 
        JMenu fileMenu = new JMenu("File");
        
        // constructor to create menu item "New" for the "File" menu
        JMenuItem newItem = new JMenuItem("New");           // create New menu item
        fileMenu.add( newItem );                            // add new item to file menu

        newItem.addActionListener
        (
                new ActionListener()
                {
                    public void actionPerformed(ActionEvent event)
                    {
                        textPanel.setText (" ");
                    }
                }
        );
        
        JMenuItem openItem = new JMenuItem("Open...");      // create Open... menu item
        fileMenu.add( openItem );                           // add open item to file menu
        openItem.addActionListener
        (
            new ActionListener() // anonymous inner class
             /****************************************************************************
              * PURPOSE:         To clear the text area on Notepad when the user clicks 
              *                  "New" from the File menu                 
              *
              * PRECONDITIONS:   The Notepad is opened, and 
              *
              * POSTCONDITIONS:  After "New" is clicked the text area will be empty
              *
              * ALGORITHM:       Click "File" menu
              *                  Click "New" menu item
              *                  Clear the text Document
              **************************************************************************/
            {
                public void actionPerformed(ActionEvent aEvent)
                {
                    // constructor for the Open Dialog Box
                    JFrame openDialog = new JFrame();   
                    
                    //set dimensions of openFile window size
                    openDialog.setSize(600,350); 
                    openDialog.setContentPane(textPanel);

                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("Open");
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    fileChooser.setApproveButtonText("Open");
                    fileChooser.setApproveButtonToolTipText("Open");
                    int result = fileChooser.showOpenDialog(openDialog);

                    if (result == JFileChooser.CANCEL_OPTION)
                    
                        System.exit(1);
        
                    
                        

                    File fileName = fileChooser.getSelectedFile();
                    openDialog.setVisible(true);

                    if( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
                    {
                        JOptionPane.showMessageDialog(null, "Invalid Name", "Error",
                                JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                    }




                    }

                


                    
                
            }
        ); // end anonymous inner class



        JMenuItem saveItem = new JMenuItem("Save");         // create Save menu item
        fileMenu.add( saveItem );                           // add save item to file menu
        saveItem.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e) {
            JFrame saveWindow = new JFrame();
            savewindow.setSize(200,200); //set openFile window size
            // openwindow.setContentPane(content);

            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Save");
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setApproveButtonText("Save");
            fileChooser.setApproveButtonToolTipText("Save:");
            int myReturnVal = fileChooser.showSaveDialog(saveWindow);
            if (myReturnVal == JFileChooser.APPROVE_OPTION) {
            File myFile = fileChooser.getSelectedFile(); //read the file
        }





}
});



        JMenuItem saveAsItem = new JMenuItem("Save As..."); // create Save As... menu item
        fileMenu.add( saveAsItem );                         // add save as item to file menu
        JMenuItem exitItem = new JMenuItem("Exit");         // create Exit menu item
        fileMenu.add( exitItem );                           // add exit item to file menu




        exitItem.addActionListener
        /**************************************************************************
         * PURPOSE:         To exit Notepad when the user clicks "Exit" from the
         *                  File menu
         *
         * PRECONDITIONS:   The Notepad is opened
         *
         * POSTCONDITIONS:  The Notepad will close once the user clicks "Exit"
         *
         * ALGORITHM:       Click "Exit"
         *                  Exit the program
         **************************************************************************/
        (
            new ActionListener() // anonymous inner class
            {
                // terminate application when user clicks exitItem
                public void actionPerformed(ActionEvent aEvent)
                {
                    System.exit(0);
                }
            } // end anonymous inner class
        ); // end call to addActionListener

        JMenuBar bar = new JMenuBar();
        setJMenuBar(bar);
        bar.add(fileMenu);

        JMenu helpMenu = new JMenu("Help");               // create the help menu
        JMenuItem aboutItem = new JMenuItem("About...");  // create About menu item
        helpMenu.add(aboutItem);                          // add about item to file menu
        bar.add(helpMenu);                                // add help menu to menu bar

        // if About is clicked, implement the action listener for it
        aboutItem.addActionListener(
        /**************************************************************************
         * PURPOSE:         To create a dialog box showing the name of the software
         *                  version and creator
         *
         * PRECONDITIONS:   The user has clicked "About..." on the Help menu.
         *                  The action listener has been implemented for the help
         *                  menu
         *
         * OUTPUT:          The dialog box will show on the screen with the following
         *                  text:
         * 
         *                  NetBeans IDE
         *                  Version 6.9.1
         *                  Matthew Rivera
         *
         * POSTCONDITIONS:  The dialog box will exit once the user clicks "OK" on it
         * 
         * ALGORITHM:       Show dialog box
         *                  Close dialog box when user clicks "OK"
         **************************************************************************/

         new ActionListener() // anonymous inner class
         {
            // display message dialog when user selects About...
            public void actionPerformed( ActionEvent event )
            {
                // shows the messageDialog on the screen
               JOptionPane.showMessageDialog( NotepadIO.this,
                  "NetBeans IDE\nVersion 6.9.1\nMatthew Rivera",
                  "About", JOptionPane.PLAIN_MESSAGE );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener for the About item

      // create the Format menu
      JMenu formatMenu = new JMenu("Format");

        // array listing string colors
      String[] colors = { "Black", "Blue", "Red", "Green" };

      JMenu colorMenu = new JMenu( "Color" ); // create color menu
      colorMenu.setMnemonic( 'C' ); // set mnemonic to C

      // create radio button menu items for colors
      colorItems = new JRadioButtonMenuItem[ colors.length ];
      colorButtonGroup = new ButtonGroup(); // manages colors
      ItemHandler itemHandler = new ItemHandler(); // handler for colors

      // create color radio button menu items
      for ( int count = 0; count < colors.length; count++ )
      {
         colorItems[ count ] =
            new JRadioButtonMenuItem( colors[ count ] ); // create item
         colorMenu.add( colorItems[ count ] ); // add item to color menu
         colorButtonGroup.add( colorItems[ count ] ); // add to group
         colorItems[ count ].addActionListener( itemHandler );
      } // end for

      colorItems[ 0 ].setSelected( true ); // select first Color item

      formatMenu.add( colorMenu ); // add color menu to format menu
      formatMenu.addSeparator(); // add separator in menu

      JMenu fontMenu = new JMenu( "Font" ); // create font menu
      String[] styleNames = { "Bold", "Italic" }; // names of styles
      styleItems = new JCheckBoxMenuItem[ styleNames.length ];
      StyleHandler styleHandler = new StyleHandler(); // style handler

      // create style checkbox menu items
      for ( int count = 0; count < styleNames.length; count++ )
      {
         styleItems[ count ] =
            new JCheckBoxMenuItem( styleNames[ count ] ); // for style
         fontMenu.add( styleItems[ count ] ); // add to font menu
         styleItems[ count ].addItemListener( styleHandler ); // handler
      } // end for

      formatMenu.add( fontMenu ); // add Font menu to Format menu
      bar.add( formatMenu ); // add Format menu to menu bar
   } // end MenuFrame constructor

    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

   // inner class to handle action events from menu items
   private class ItemHandler implements ActionListener
   {
      // process color and font selections
      public void actionPerformed( ActionEvent event )
      {
         // process color selection
         for ( int count = 0; count < colorItems.length; count++ )
         {
            if ( colorItems[ count ].isSelected() )
            {
               displayJLabel.setForeground( colorValues[ count ] );
               break;
            } // end if
         } // end for
         repaint(); // redraw application
      } // end method actionPerformed
   } // end class ItemHandler

   // inner class to handle item events from checkbox menu items
   private class StyleHandler implements ItemListener
   {
      // process font style selections
      public void itemStateChanged( ItemEvent e )
      {
         String name = displayJLabel.getFont().getName(); // current Font
         Font font; // new font based on user selections

         // determine which CheckBoxes are checked and create Font
         if ( styleItems[ 0 ].isSelected() &&
              styleItems[ 1 ].isSelected() )
            font = new Font( name, Font.BOLD + Font.ITALIC, 10 );
         else if ( styleItems[ 0 ].isSelected() )
            font = new Font( name, Font.BOLD, 10 );
         else if ( styleItems[ 1 ].isSelected() )
            font = new Font( name, Font.ITALIC, 10 );
         else
            font = new Font( name, Font.PLAIN, 10 );

         displayJLabel.setFont( font );
         repaint(); // redraw application
      } // end method itemStateChanged
   } // end class StyleHandler
}
/***************************************************************************/
  

  import javax.swing.JFrame;

/******************************************************************************
 *
     */


public class NotepadIOTest
{

    public static void main(String[] args)
    {
        NotepadIO app = new NotepadIO();
        app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        app.setVisible(true);

    }

}



I did implement the "New" menu item from the "File" menu, so that the Notepad clears the text area when I click it. However, I'm still having trouble implementing the "Open", "Save", and "Save As..." menu items correctly. I click on Open, the Open Dialog box appears, but the Notepad Window is blank. I can't save the text I type in the Notepad window either. I clicked on "Save" on the File Menu, but after I specify a file name, it doesn't save it in my chosen directory. The items in the File Menu must be implemented like a real Notepad application would do? Does the file need to have a .txt extension in order for my program to work properly?

Here are some links I found:

http://www.javajazzu...e4/page69.shtml
http://www.javapract...FF6F2CDF7?Id=42
http://www.codeguru....hp/t-36041.html



View Postmacosxnerd101, on 19 April 2011 - 10:57 PM, said:

You don't have variables for any of the ones causing the Cannot Find Symbol errors.


Quote

E:\Adv Java\NotepadIOTest\src\NotepadIO.java:133: cannot find symbol
symbol: method dispose()
this.dispose(); // dispose all resources and close the application

In the given context, this refers to your ActionListener, not the JFrame. If you remove this from your dispose() invocation, it will invoke the dispose() method for the encapsulating Object- your JFrame.

Same thing applies here:

Quote

E:\Adv Java\NotepadIOTest\src\NotepadIO.java:138: showOpenDialog(java.awt.Component) in javax.swing.JFileChooser cannot be applied to (<anonymous java.awt.event.ActionListener>)
int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel)

Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10574
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Creating a Java Notepad with file I/O and menus

Posted 21 April 2011 - 08:50 PM

For open, you have to actually read the File using either Scanner or an appopriate tool in the java.io package, and set the text of the JTextArea to the contents you read from the File.

For the Save/Save As options, you still need to write the data to the File. Again, using the appropriate java.io tools. Also, check out the JFileChooser.showSaveDialog() method, which can help you obtain where to write the File.
Was This Post Helpful? 1
  • +
  • -

#9 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: Creating a Java Notepad with file I/O and menus

Posted 22 April 2011 - 08:04 PM

After using the Scanner in the openFile block

  JMenuItem openItem = new JMenuItem("Open...");      // create Open... menu item
        fileMenu.add( openItem );                           // add open item to file menu
        openItem.addActionListener
        (
            new ActionListener() // anonymous inner class
             /****************************************************************************
              * PURPOSE:         To clear the text area on Notepad when the user clicks 
              *                  "New" from the File menu                 
              *
              * PRECONDITIONS:   The Notepad is opened, and 
              *
              * POSTCONDITIONS:  After "New" is clicked the text area will be empty
              *
              * ALGORITHM:       Click "File" menu
              *                  Click "New" menu item
              *                  Clear the text Document
              **************************************************************************/
            {
                public void actionPerformed(ActionEvent aEvent)
                {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("Open");
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    fileChooser.setApproveButtonText("Open");
                    //fileChooser.setApproveButtonToolTipText("Open");
                    int result = fileChooser.showOpenDialog(openDialog);

                    if (result == JFileChooser.CANCEL_OPTION)
                    
                        System.exit(1);
        
                    
                        

                    File fileName = fileChooser.getSelectedFile();
                    openDialog.setVisible(true);

                    if( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
                    {
                        JOptionPane.showMessageDialog(null, "Invalid Name", "Error",
                                JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                    }

			this.textPanel.setText(""); // clear the TextArea before applying the file contents
			try {
				// create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
				Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
				while (scan.hasNext()) // while there's still something to read
					this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
			} catch (Exception ex) { // catch any exceptions, and...
				// ...write to the debug console
				System.out.println(ex.getMessage());



                    }

                


                    
                
            }
        ); // end anonymous inner class*/




        JMenuItem saveItem = new JMenuItem("Save");         // create Save menu item
        fileMenu.add( saveItem );                           // add save item to file menu
        saveItem.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e) {
            JFrame saveWindow = new JFrame();
            savewindow.setSize(200,200); //set openFile window size
            // openwindow.setContentPane(content);

            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Save");
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setApproveButtonText("Save");
            fileChooser.setApproveButtonToolTipText("Save:");
            int myReturnVal = fileChooser.showSaveDialog(saveWindow);
            if (myReturnVal == JFileChooser.APPROVE_OPTION) {
            File myFile = fileChooser.getSelectedFile(); //read the file
        }





}
});





...these are the errors I get:

E:\Adv Java\NotepadIOTest\src\NotepadIO.java:186: illegal start of type
); // end anonymous inner class*/
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:192: <identifier> expected
fileMenu.add( saveItem ); // add save item to file menu
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:192: <identifier> expected
fileMenu.add( saveItem ); // add save item to file menu
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:193: <identifier> expected
saveItem.addActionListener(new ActionListener()
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:193: illegal start of type
saveItem.addActionListener(new ActionListener()
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:193: ')' expected
saveItem.addActionListener(new ActionListener()
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:193: ';' expected
saveItem.addActionListener(new ActionListener()
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:193: illegal start of type
saveItem.addActionListener(new ActionListener()
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:193: <identifier> expected
saveItem.addActionListener(new ActionListener()
E:\Adv Java\NotepadIOTest\src\NotepadIO.java:194: ';' expected
{
10 errors

View Postmacosxnerd101, on 21 April 2011 - 08:50 PM, said:

For open, you have to actually read the File using either Scanner or an appopriate tool in the java.io package, and set the text of the JTextArea to the contents you read from the File.

For the Save/Save As options, you still need to write the data to the File. Again, using the appropriate java.io tools. Also, check out the JFileChooser.showSaveDialog() method, which can help you obtain where to write the File.

Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Creating a Java Notepad with file I/O and menus

Posted 22 April 2011 - 08:38 PM

Cut and pasted your code in Eclipse and it got lost. Sorry but this code is so horrible then it even you screw up my Eclipse that is usually quite robust

You have few () defining your inner classes that should be delimitated by {} not ()

so many inner classes are really a bad design
Anyhow... check your inner classes they should be within {} not ()
Was This Post Helpful? 0
  • +
  • -

#11 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10574
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Creating a Java Notepad with file I/O and menus

Posted 22 April 2011 - 08:41 PM

Also, you are way overcommenting your code. Comments should help clarify ambiguous sections of code by saying why you are doing something, not what you are doing. Telling us you are reading in a file and what the result should be is too much. Maybe just a single-line comment if you are so inclined. But 10 lines of comments for that is overkill. Overdoing it with comments can produce just as ambiguous/hard to read code as grossly undercommented code. Plus, you code should be somewhat self-documenting with your spacing/indentation conventions and descriptive naming conventions.
Was This Post Helpful? 1
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Creating a Java Notepad with file I/O and menus

Posted 22 April 2011 - 08:49 PM

View Postmacosxnerd101, on 22 April 2011 - 10:41 PM, said:

Also, you are way overcommenting your code. Comments should help clarify ambiguous sections of code by saying why you are doing something, not what you are doing. Telling us you are reading in a file and what the result should be is too much. Maybe just a single-line comment if you are so inclined. But 10 lines of comments for that is overkill. Overdoing it with comments can produce just as ambiguous/hard to read code as grossly undercommented code. Plus, you code should be somewhat self-documenting with your spacing/indentation conventions and descriptive naming conventions.

macosxnerd101 is 100% right
I had to remove so many lines of comments to test your code
and
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;


can more easiliest to read replace
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1