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?

New Topic/Question
Reply



MultiQuote







|