【问题标题】:Create a save/save as dialog box in java that save a newly created file or an edited file在java中创建一个保存/另存为对话框,用于保存新创建的文件或编辑的文件
【发布时间】:2013-04-11 02:51:28
【问题描述】:

Java 初学者:请帮我忙了几天,我的大脑已经死了。 我创建了一个具有 3 个菜单的 Java 程序(在 Eclipse 中):文件、编辑、帮助 单击文件后,它会显示 4menuBar: 'new,open,save,save as & exit。

在帮助菜单上有一个菜单栏,上面写着“关于 javaEdit” 我所有的菜单栏都可以正常工作,除了保存、另存为和“关于 javaEdit” 我需要一些代码或一个清晰的分步说明来解释如何拥有我的保存并另存为工作。

保存应该保存新创建的文件或编辑过的文件,最后我可能会喜欢“关于 JavaEdit”,一旦点击就会显示“谢谢,这是 java”之类的消息。我喜欢类似

private void doSave(){code here} 

private void doSaveAs (){ 

因为我在 if else if 语句中有这些项目。

如何在java中创建一个保存/另存为对话框来保存新创建的文件或编辑过的文件?

下面是我的完整代码:

import java.awt.*;
import java.awt.event
import java.io.*;

public class JavaEdit extends Frame implements ActionListener {

    String clipBoard;
    String fileName;
    TextArea text;
    MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
    MenuItem selectAllMI, cutMI, copyMI, deleteMI, pasteMI;
    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);
        selectAllMI = editMenu.add(new MenuItem("Select all"));
        selectAllMI.addActionListener(this);

        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);

    // 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(text, BorderLayout.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 == saveMI) {
            doSave();
    }
    else if(source == saveAsMI){
    doSaveAs();
    }
        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();
        }
    }

    /**
     * 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(clipBoard, text.getSelectionStart(),
                              text.getSelectionEnd());
        }
    }

    /**
     * class for message dialog
     */
    class MessageDialog extends Dialog implements ActionListener {
        private Label message;
        private Button okButton;

     // Constructor
        public MessageDialog(Frame parent, String title, String messageString) {
            super(parent, title, true);
            setSize(400, 100);
            setLocation(150, 150);
            setLayout(new BorderLayout());

            message = new Label(messageString, Label.CENTER);
            add(message, BorderLayout.CENTER);

            Panel panel = new Panel(new FlowLayout(FlowLayout.CENTER));
            add(panel, BorderLayout.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-80, size.height-80);
        frame.setLocation(20, 20);

        // add window closing listener

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

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

【问题讨论】:

  • 为什么这个代码是 AWT?为什么 AWT 有 FileDialog 时要添加 JFileChooser 标签?
  • 另外,考虑重构以使用Action

标签: java swing jfilechooser dialog


【解决方案1】:

即使是 AWT 程序也可以使用 Action 来封装功能并防止(而不是抑制)leaking this in constructor。例如,

private static JavaEdit frame;
...
public JavaEdit() {
    ...
    saveMI = fileMenu.add(new MenuItem("Save"));
    saveMI.addActionListener(new SaveAction());
    ...
}

private static class SaveAction extends AbstractAction {

    @Override
    public void actionPerformed(ActionEvent e) {
        FileDialog fDialog = new FileDialog(frame, "Save", FileDialog.SAVE);
        fDialog.setVisible(true);
        String path = fDialog.getDirectory() + fDialog.getFile();
        File f = new File(path);
        // f.createNewFile(); etc.
    }

public static void main(String[] argv) {
    // create frame
    frame = new JavaEdit();
    ...
    // show the frame
    frame.pack();
    frame.setVisible(true);
}

参见HTMLDocumentEditor,引用here,例如相关操作的实现。

【讨论】:

  • 谢谢你的垃圾神,你给我指出了正确的方向。我现在可以显示保存对话框,但它不能保存任何文件!如果打开文件进行编辑,我希望它能够以原始文件名保存文件,但如果创建了新文件,我希望出现“另存为”选项。这是调出保存对话框的代码 'private void doSave(){ FileDialog fDialog = new FileDialog(frame, "Save", FileDialog.SAVE); fDialog.setVisible(true);字符串名称 = fDialog.getDirectory()+fDialog.getFile();文件文件 = 新文件(名称);'
  • 对,你必须创建和写入文件。例如,参见HTMLDocumentEditor,引用here。使用任何新代码更新您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
相关资源
最近更新 更多