仿照Windows中的记事本,编写一个Java程序记事本。代码
时间: 2024-03-22 11:41:43 浏览: 80
以下是一个简单的Java程序记事本的代码示例:
```java
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
public class JavaNotepad extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private JFileChooser fileChooser;
private String fileName;
private boolean hasSaved;
private String appName = "Java Notepad";
public JavaNotepad() {
super();
setTitle(appName);
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// create menu bar
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newFile = new JMenuItem("New");
newFile.addActionListener(this);
newFile.setAccelerator(KeyStroke.getKeyStroke('N', java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fileMenu.add(newFile);
JMenuItem openFile = new JMenuItem("Open");
openFile.addActionListener(this);
openFile.setAccelerator(KeyStroke.getKeyStroke('O', java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fileMenu.add(openFile);
JMenuItem saveFile = new JMenuItem("Save");
saveFile.addActionListener(this);
saveFile.setAccelerator(KeyStroke.getKeyStroke('S', java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fileMenu.add(saveFile);
JMenuItem saveAsFile = new JMenuItem("Save As");
saveAsFile.addActionListener(this);
fileMenu.add(saveAsFile);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(this);
fileMenu.add(exit);
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
JMenuItem cut = new JMenuItem("Cut");
cut.addActionListener(this);
cut.setAccelerator(KeyStroke.getKeyStroke('X', java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
editMenu.add(cut);
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.setAccelerator(KeyStroke.getKeyStroke('C', java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
editMenu.add(copy);
JMenuItem paste = new JMenuItem("Paste");
paste.addActionListener(this);
paste.setAccelerator(KeyStroke.getKeyStroke('V', java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
editMenu.add(paste);
JMenuItem selectAll = new JMenuItem("Select All");
selectAll.addActionListener(this);
selectAll.setAccelerator(KeyStroke.getKeyStroke('A', java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
editMenu.add(selectAll);
menuBar.add(editMenu);
setJMenuBar(menuBar);
// create text area
textArea = new JTextArea();
textArea.setFont(new Font("Arial", Font.PLAIN, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
getContentPane().add(scrollPane, BorderLayout.CENTER);
// create file chooser dialog
fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files (*.txt)", "txt"));
fileChooser.setAcceptAllFileFilterUsed(false);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "New":
newFile();
break;
case "Open":
openFile();
break;
case "Save":
saveFile();
break;
case "Save As":
saveAsFile();
break;
case "Exit":
exit();
break;
case "Cut":
cut();
break;
case "Copy":
copy();
break;
case "Paste":
paste();
break;
case "Select All":
selectAll();
break;
default:
break;
}
}
private void newFile() {
if (!hasSaved && textArea.getText().length() > 0) {
int result = JOptionPane.showConfirmDialog(this, "Do you want to save the changes?");
if (result == JOptionPane.YES_OPTION) {
saveFile();
} else if (result == JOptionPane.CANCEL_OPTION) {
return;
}
}
textArea.setText("");
fileName = null;
setTitle(appName);
hasSaved = false;
}
private void openFile() {
if (!hasSaved && textArea.getText().length() > 0) {
int result = JOptionPane.showConfirmDialog(this, "Do you want to save the changes?");
if (result == JOptionPane.YES_OPTION) {
saveFile();
} else if (result == JOptionPane.CANCEL_OPTION) {
return;
}
}
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
fileName = fileChooser.getSelectedFile().getPath();
setTitle(fileName + " - " + appName);
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
textArea.setText(sb.toString());
hasSaved = true;
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveFile() {
if (fileName == null) {
saveAsFile();
return;
}
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName)))) {
writer.print(textArea.getText());
hasSaved = true;
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void saveAsFile() {
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
fileName = fileChooser.getSelectedFile().getPath();
if (!fileName.endsWith(".txt")) {
fileName += ".txt";
}
setTitle(fileName + " - " + appName);
saveFile();
}
}
private void exit() {
if (!hasSaved && textArea.getText().length() > 0) {
int result = JOptionPane.showConfirmDialog(this, "Do you want to save the changes?");
if (result == JOptionPane.YES_OPTION) {
saveFile();
} else if (result == JOptionPane.CANCEL_OPTION) {
return;
}
}
dispose();
}
private void cut() {
textArea.cut();
}
private void copy() {
textArea.copy();
}
private void paste() {
textArea.paste();
}
private void selectAll() {
textArea.selectAll();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JavaNotepad notepad = new JavaNotepad();
notepad.setVisible(true);
}
}
```
该程序具有基本的文件操作、编辑操作和界面元素,并且可以在Windows、Mac OS X和Linux等操作系统上运行。您可以根据自己的需求进行调整和扩展。
阅读全文