CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Code Help

  1. #1
    Join Date
    Apr 2013
    Posts
    2

    Exclamation Code Help

    Hello,

    Below is the code that I am currently working on. At this moment I am having great difficulty implementing the Save/Save As menu items to the File Menu.

    "Complete the implementation for the Save and Save As menu items in the File menu. When Save As is selected, a file selection dialog box should be displayed and the text content saved to the file chosen. When Save is selected, the text content should be saved to the current file. If no current file exists, a dialog box should appear for file selection like Save As."

    PHP Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;

    import javax.swing.JOptionPane;

    public class 
    JavaEdit extends Frame implements ActionListener {

    String clipBoard;
    String fileName;
    TextArea text;
    MenuItem newMIopenMIsaveMIsaveAsMIexitMI;
    MenuItem cutMIcopyMIdeleteMIpasteMIselectallMI;
    MenuItem aboutjavaeditMI;

    /**
    * Constructor
    */
    public JavaEdit() {
    super("JavaEdit"); // set frame title
    setLayout(new BorderLayout()); // set layout

    // create menu bar
    MenuBar menubar = new MenuBar();
    setMenuBar(menubar);

    // create file menu
    Menu fileMenu = new Menu("File");
    menubar.add(fileMenu);
    newMI fileMenu.add(new MenuItem("New"));
    newMI.addActionListener(this);
    openMI fileMenu.add(new MenuItem("Open"));
    openMI.addActionListener(this);
    fileMenu.addSeparator();
    saveMI fileMenu.add(new MenuItem("Save"));
    saveAsMI fileMenu.add(new MenuItem("Save As ..."));
    fileMenu.addSeparator();
    exitMI fileMenu.add(new MenuItem("Exit"));
    exitMI.addActionListener(this);

    // create edit menu
    Menu editMenu = new Menu("Edit");
    menubar.add(editMenu);
    cutMI editMenu.add(new MenuItem("Cut"));
    cutMI.addActionListener(this);
    copyMI editMenu.add(new MenuItem("Copy"));
    copyMI.addActionListener(this);
    pasteMI editMenu.add(new MenuItem("Paste"));
    pasteMI.addActionListener(this);
    deleteMI editMenu.add(new MenuItem("Delete"));
    deleteMI.addActionListener(this);
    selectallMI editMenu.add(new MenuItem("Select All"));
    selectallMI.addActionListener(this);
    //create help menu
    Menu helpMenu = new Menu("Help");
    menubar.add(helpMenu);
    aboutjavaeditMI helpMenu.add(new MenuItem("About JavaEdit"));
    aboutjavaeditMI.addActionListener(this);

    // create text editing area
    text = new TextArea();
    add(textBorderLayout.CENTER);
    }

    // implementing ActionListener
    public void actionPerformed(ActionEvent event) {
    Object source event.getSource();
    if(
    source == newMI) {
    clearText();
    fileName null;
    setTitle("JavaEdit"); // reset frame title
    }
    else if(
    source == openMI) {
    doOpen();
    }
    else if(
    source == exitMI) {
    System.exit(0);
    }
    else if(
    source == cutMI) {
    doCopy();
    doDelete();
    }
    else if(
    source == copyMI) {
    doCopy();
    }
    else if(
    source == pasteMI) {
    doPaste();
    }
    else if(
    source == deleteMI) {
    doDelete();
    }
    else if(
    source == selectallMI) {
    text.selectAll();

    }
    else if(
    source == aboutjavaeditMI) {
    JOptionPane.showMessageDialog(this"JavaEdit in Java, Version 2.1, 2013."
    "This is the Dialog Message"JOptionPane.PLAIN_MESSAGE);
    }
    else if(
    source == saveAsMI) {

    }
    else if(
    source == saveMI){
        

    }
    }

    /**
    * method to specify and open a file
    */
    private void doOpen() {
    // display file selection dialog
    FileDialog fDialog = new FileDialog(this"Open ..."FileDialog.LOAD);
    fDialog.setVisible(true);
    // Get the file name chosen by the user
    String name fDialog.getFile();
    // If user canceled file selection, return without doing anything.
    if(name == null)
    return;
    fileName fDialog.getDirectory() + name;

    // Try to create a file reader from the chosen file.
    FileReader reader=null;
    try {
    reader = new FileReader(fileName);
    } catch (
    FileNotFoundException ex) {
    MessageDialog dialog = new MessageDialog(this"Error Message",
    "File Not Found: "+fileName);
    dialog.setVisible(true);
    return;
    }
    BufferedReader bReader = new BufferedReader(reader);

    // Try to read from the file one line at a time.
    StringBuffer textBuffer = new StringBuffer();
    try {
    String textLine bReader.readLine();
    while (
    textLine != null) {
    textBuffer.append(textLine '\n');
    textLine bReader.readLine();
    }
    bReader.close();
    reader.close();
    } catch (
    IOException ioe) {
    MessageDialog dialog = new MessageDialog(this"Error Message",
    "Error reading file: "+ioe.toString());
    dialog.setVisible(true);
    return;
    }
    setTitle("JavaEdit: " +name); // reset frame title
    text.setText(textBuffer.toString());
    }

    /**
    * method to clear text editing area
    */
    private void clearText() {
    text.setText("");
    }

    /**
    * method to copy selected text to the clipBoard
    */
    private void doCopy() {
    clipBoard = new String(text.getSelectedText());
    }
    /**
    * method to delete selected text
    */
    private void doDelete() {
    text.replaceRange(""text.getSelectionStart(), text.getSelectionEnd());
    }

    /**
    * method to replace current selection with the contents of the clipBoard
    */
    private void doPaste() {
    if(
    clipBoard != null) {
    text.replaceRange(clipBoardtext.getSelectionStart(),
    text.getSelectionEnd());
    }
    }

    public 
    void selectAll() {
    if(
    clipBoard !=null) {
    clipBoard = new String(text.getSelectedText());
    }
    }
    /**
    * class for message dialog
    */
    class MessageDialog extends Dialog implements ActionListener {
    private 
    Label message;
    private 
    Button okButton;

    // Constructor
    public MessageDialog(Frame parentString titleString messageString) {
    super(parenttitletrue);
    setSize(400100);
    setLocation(150150);
    setLayout(new BorderLayout());

    message = new Label(messageStringLabel.CENTER);
    add(messageBorderLayout.CENTER);

    Panel panel = new Panel(new FlowLayout(FlowLayout.CENTER));
    add(panelBorderLayout.SOUTH);
    okButton = new Button(" OK ");
    okButton.addActionListener(this);
    panel.add(okButton);
    }

    // implementing ActionListener
    public void actionPerformed(ActionEvent event) {
    setVisible(false);
    dispose();
    }
    }

    /**
    * the main method
    */
    public static void main(String[] argv) {
    // create frame
    JavaEdit frame = new JavaEdit();
    Dimension size Toolkit.getDefaultToolkit().getScreenSize();
    frame.setSize(size.width-80size.height-80);
    frame.setLocation(2020);

    // add window closing listener
    frame.addWindowListener(new WindowAdapter() {
    public 
    void windowClosing(WindowEvent e) {
    System.exit(0);
    }
    });

    // show the frame
    frame.setVisible(true);
    }


  2. #2
    Join Date
    Apr 2013
    Location
    Cambridge
    Posts
    4

    Re: Code Help

    For the 'save as' dialog, you can use a JFileChooser - see http://docs.oracle.com/javase/tutori...lechooser.html for the details. Then you'll just need to make your JavaEdit class a listener for the 'save' and 'save as' menu items like you've done with the others, and add logic to the actionPerformed function to either save or show the file chooser then save according to the rules mentioned in your post.

    Incidentally, you've got a lot of repeated code that you could factor out to make it a bit cleaner - for instance, you're often repeating lines like:

    Code:
    newMI = fileMenu.add(new MenuItem("New")); 
    newMI.addActionListener(this);
    You could simplify this out an have a function for adding new menu items like this:

    Code:
    void addMenuItem(Menu menu, String name) {
        MenuItem newItem = menu.add(new MenuItem(name));
        newItem.addActionListener(this);
    }
    And then the code for adding the 'New' command to the file menu would just be addMenuItem(fileMenu, "New"). This approach would mean you'd have to change the actionPerformed method though - instead of checking what the source of the event was, you could call "event.getActionCommand()" (on the event being passed in) to get the name of the menu item being clicked, and use that to decide what to do.

    You could then clean it up even further by splitting the code for making the menus into different methods - createFileMenu(), createEditMenu() etc. - and then make a createMenus() method which calls them all so that your constructor only needs to call createMenus(). You could even simplify it further by having one method, createMenu(), which takes a menu name and a list of menu item names and adds them all to a new menu with listeners set up. Would make the code tidier and a bit easier to modify if you ever need to add more menu options

  3. #3
    Join Date
    Apr 2013
    Posts
    2

    Re: Code Help

    I've actually tried earlier using the JFileChooser method, but still it doesn't work for me. Are there other any alternatives because I'm starting to run out of ideas.

  4. #4
    Join Date
    Apr 2013
    Location
    Cambridge
    Posts
    4

    Re: Code Help

    What problems have you been having? You should be able to just create one and call fc.showSaveDialog(this), then you can get the file the user selected with fc.getSelectedFile().

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured