gpt4 book ai didi

Java 文件对话框另存为

转载 作者:行者123 更新时间:2023-12-02 12:02:59 25 4
gpt4 key购买 nike

我正在为我的 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 selectAll, cutMI, copyMI, deleteMI, pasteMI;
MenuItem about;

/**
* 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"));
saveMI.addActionListener(this);
saveAsMI = fileMenu.add(new MenuItem("Save As ..."));
saveAsMI.addActionListener(this);
fileMenu.addSeparator();
exitMI = fileMenu.add(new MenuItem("Exit"));
exitMI.addActionListener(this);

// create edit menu
Menu editMenu = new Menu("Edit");
menubar.add(editMenu);
selectAll = editMenu.add(new MenuItem("Select All"));
selectAll.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);

Menu helpMenu = new Menu("Help");
menubar.add(helpMenu);
about = helpMenu.add(new MenuItem("About"));
about.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 == saveAsMI) {

doSaveAs();
}
else if (source == saveMI) {
doSave();
}
else if(source == exitMI) {
System.exit(0);
}
else if(source == selectAll) {
doSelect();
}
else if(source == cutMI) {
doCopy();
doDelete();
}
else if(source == copyMI) {
doCopy();
}
else if(source == pasteMI) {
doPaste();
}
else if(source == deleteMI) {
doDelete();
}
else if(source == about){
MessageDialog dialog = new MessageDialog(this, "About",
"JavaEdit in Java, Version 2.0, 2017");
dialog.setVisible(true);
return;

}

}

/**
* 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());
}
private void doSaveAs() {

FileDialog fDialog = new FileDialog(this, "Save As ...", FileDialog.SAVE);
fDialog.setVisible(true);

fileName = fDialog.getFile();
String name = fileName.toString();

setTitle("JavaEdit: " + name); // reset frame title
fDialog.setFile(name);


FileWriter fileCharStream = null; // File stream for writing file
try {

fileCharStream = new FileWriter(fileName); // May throw IOException
// Use file output stream
fileCharStream.write(text.getText());

} catch (IOException excpt) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
fileName);
dialog.setVisible(true);
return;
} finally {
closeFileWriter(fileCharStream); // Ensure file is closed!
}

}


private void doSave() {

if(fileName == null )
{
doSaveAs();
}
FileWriter out = null;
try {
out =new FileWriter(fileName);

out.write(text.getText());

}
catch (IOException excpt) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
fileName);
dialog.setVisible(true);
return;
} finally {
closeFileWriter(out); // Ensure file is closed!
}// Ensure file is closed!


}
static void closeFileWriter(FileWriter fileName) {
try {
if (fileName != null) { // Ensure "file" references a valid object

fileName.close(); // close() may throw IOException if fails

}
} catch (IOException closeExcpt) {
closeExcpt.getMessage();
}

return;
}


private void doSelect() {
text.selectAll();
}

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


this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
}
});


}

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

最佳答案

简单地检查返回的文件是否为空:

String name = fDialog.getFile();
// if Cancel is pressed we just exit
if (name == null) {
return;
}
// otherwise we save it
fileName = name;
...

关于Java 文件对话框另存为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47113416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com