用java实现简易记事本
时间: 2023-10-02 16:03:47 浏览: 106
这是一个简单的Java Swing记事本示例:
```java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultEditorKit;
public class SimpleNotepad extends JFrame implements ActionListener {
private JTextArea textArea;
private JLabel statusBar;
private JFileChooser fileChooser;
private String currentFile = "";
private JMenuBar menuBar;
private JMenu fileMenu, editMenu, formatMenu, viewMenu, helpMenu;
private JMenuItem newFile, openFile, saveFile, saveAsFile, pageSetup, printFile, exitProgram;
private JMenuItem undoEdit, cutEdit, copyEdit, pasteEdit, deleteEdit, findEdit, findNextEdit, replaceEdit, gotoEdit, selectAllEdit, timeDateEdit;
private JMenuItem wordWrapFormat, fontFormat;
private JMenuItem statusBarView;
private JMenuItem aboutHelp;
public SimpleNotepad() {
super("Simple Notepad");
// Create the text area and set the font
textArea = new JTextArea();
textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
// Add the text area to a scroll pane
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(800, 600));
// Add the scroll pane to the frame
add(scrollPane, BorderLayout.CENTER);
// Create the status bar
statusBar = new JLabel("Ready");
statusBar.setBorder(BorderFactory.createEtchedBorder(Color.WHITE, Color.BLACK));
add(statusBar, BorderLayout.SOUTH);
// Create the file chooser
fileChooser = new JFileChooser(".");
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files (*.txt)", "txt"));
// Create the menu bar
menuBar = new JMenuBar();
// Create the file menu
fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
newFile = new JMenuItem("New");
newFile.setAccelerator(KeyStroke.getKeyStroke("control N"));
newFile.addActionListener(this);
fileMenu.add(newFile);
openFile = new JMenuItem("Open");
openFile.setAccelerator(KeyStroke.getKeyStroke("control O"));
openFile.addActionListener(this);
fileMenu.add(openFile);
saveFile = new JMenuItem("Save");
saveFile.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveFile.addActionListener(this);
fileMenu.add(saveFile);
saveAsFile = new JMenuItem("Save As...");
saveAsFile.addActionListener(this);
fileMenu.add(saveAsFile);
fileMenu.addSeparator();
pageSetup = new JMenuItem("Page Setup...");
pageSetup.addActionListener(this);
fileMenu.add(pageSetup);
printFile = new JMenuItem("Print...");
printFile.setAccelerator(KeyStroke.getKeyStroke("control P"));
printFile.addActionListener(this);
fileMenu.add(printFile);
fileMenu.addSeparator();
exitProgram = new JMenuItem("Exit");
exitProgram.setAccelerator(KeyStroke.getKeyStroke("alt F4"));
exitProgram.addActionListener(this);
fileMenu.add(exitProgram);
menuBar.add(fileMenu);
// Create the edit menu
editMenu = new JMenu("Edit");
editMenu.setMnemonic('E');
undoEdit = new JMenuItem("Undo");
undoEdit.setAccelerator(KeyStroke.getKeyStroke("control Z"));
undoEdit.addActionListener(this);
editMenu.add(undoEdit);
editMenu.addSeparator();
cutEdit = new JMenuItem(new DefaultEditorKit.CutAction());
cutEdit.setText("Cut");
cutEdit.setAccelerator(KeyStroke.getKeyStroke("control X"));
editMenu.add(cutEdit);
copyEdit = new JMenuItem(new DefaultEditorKit.CopyAction());
copyEdit.setText("Copy");
copyEdit.setAccelerator(KeyStroke.getKeyStroke("control C"));
editMenu.add(copyEdit);
pasteEdit = new JMenuItem(new DefaultEditorKit.PasteAction());
pasteEdit.setText("Paste");
pasteEdit.setAccelerator(KeyStroke.getKeyStroke("control V"));
editMenu.add(pasteEdit);
deleteEdit = new JMenuItem("Delete");
deleteEdit.setAccelerator(KeyStroke.getKeyStroke("DELETE"));
deleteEdit.addActionListener(this);
editMenu.add(deleteEdit);
editMenu.addSeparator();
findEdit = new JMenuItem("Find...");
findEdit.setAccelerator(KeyStroke.getKeyStroke("control F"));
findEdit.addActionListener(this);
editMenu.add(findEdit);
findNextEdit = new JMenuItem("Find Next");
findNextEdit.setAccelerator(KeyStroke.getKeyStroke("F3"));
findNextEdit.addActionListener(this);
editMenu.add(findNextEdit);
replaceEdit = new JMenuItem("Replace...");
replaceEdit.setAccelerator(KeyStroke.getKeyStroke("control H"));
replaceEdit.addActionListener(this);
editMenu.add(replaceEdit);
gotoEdit = new JMenuItem("Go To...");
gotoEdit.setAccelerator(KeyStroke.getKeyStroke("control G"));
gotoEdit.addActionListener(this);
editMenu.add(gotoEdit);
editMenu.addSeparator();
selectAllEdit = new JMenuItem("Select All");
selectAllEdit.setAccelerator(KeyStroke.getKeyStroke("control A"));
selectAllEdit.addActionListener(this);
editMenu.add(selectAllEdit);
timeDateEdit = new JMenuItem("Time/Date");
timeDateEdit.setAccelerator(KeyStroke.getKeyStroke("F5"));
timeDateEdit.addActionListener(this);
editMenu.add(timeDateEdit);
menuBar.add(editMenu);
// Create the format menu
formatMenu = new JMenu("Format");
formatMenu.setMnemonic('O');
wordWrapFormat = new JMenuItem("Word Wrap");
wordWrapFormat.addActionListener(this);
formatMenu.add(wordWrapFormat);
fontFormat = new JMenuItem("Font...");
fontFormat.addActionListener(this);
formatMenu.add(fontFormat);
menuBar.add(formatMenu);
// Create the view menu
viewMenu = new JMenu("View");
viewMenu.setMnemonic('V');
statusBarView = new JMenuItem("Status Bar");
statusBarView.addActionListener(this);
viewMenu.add(statusBarView);
menuBar.add(viewMenu);
// Create the help menu
helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
aboutHelp = new JMenuItem("About Simple Notepad");
aboutHelp.addActionListener(this);
helpMenu.add(aboutHelp);
menuBar.add(helpMenu);
// Add the menu bar to the frame
setJMenuBar(menuBar);
// Set the frame properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newFile) {
newFile();
} else if (e.getSource() == openFile) {
openFile();
} else if (e.getSource() == saveFile) {
saveFile();
} else if (e.getSource() == saveAsFile) {
saveAsFile();
} else if (e.getSource() == pageSetup) {
pageSetup();
} else if (e.getSource() == printFile) {
printFile();
} else if (e.getSource() == exitProgram) {
exitProgram();
} else if (e.getSource() == undoEdit) {
undoEdit();
} else if (e.getSource() == deleteEdit) {
deleteEdit();
} else if (e.getSource() == findEdit) {
findEdit();
} else if (e.getSource() == findNextEdit) {
findNextEdit();
} else if (e.getSource() == replaceEdit) {
replaceEdit();
} else if (e.getSource() == gotoEdit) {
gotoEdit();
} else if (e.getSource() == selectAllEdit) {
selectAllEdit();
} else if (e.getSource() == timeDateEdit) {
timeDateEdit();
} else if (e.getSource() == wordWrapFormat) {
wordWrapFormat();
} else if (e.getSource() == fontFormat) {
fontFormat();
} else if (e.getSource() == statusBarView) {
statusBarView();
} else if (e.getSource() == aboutHelp) {
aboutHelp();
}
}
private void newFile() {
currentFile = "";
textArea.setText("");
setTitle("Simple Notepad");
}
private void openFile() {
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
StringBuilder text = new StringBuilder();
while ((line = reader.readLine()) != null) {
text.append(line).append("\n");
}
reader.close();
textArea.setText(text.toString());
currentFile = file.getAbsolutePath();
setTitle("Simple Notepad - " + file.getName());
} catch (IOException e) {
statusBar.setText("Error: " + e.getMessage());
}
}
}
private void saveFile() {
if (currentFile.isEmpty()) {
saveAsFile();
} else {
try {
FileWriter writer = new FileWriter(currentFile);
writer.write(textArea.getText());
writer.close();
setTitle("Simple Notepad - " + new File(currentFile).getName());
} catch (IOException e) {
statusBar.setText("Error: " + e.getMessage());
}
}
}
private void saveAsFile() {
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FileWriter writer = new FileWriter(file);
writer.write(textArea.getText());
writer.close();
currentFile = file.getAbsolutePath();
setTitle("Simple Notepad - " + file.getName());
} catch (IOException e) {
statusBar.setText("Error: " + e.getMessage());
}
}
}
private void pageSetup() {
// TODO: Implement page setup functionality
}
private void printFile() {
// TODO: Implement printing functionality
}
private void exitProgram() {
System.exit(0);
}
private void undoEdit() {
// TODO: Implement undo functionality
}
private void deleteEdit() {
textArea.replaceSelection("");
}
private void findEdit() {
// TODO: Implement find functionality
}
private void findNextEdit() {
// TODO: Implement find next functionality
}
private void replaceEdit() {
// TODO: Implement replace functionality
}
private void gotoEdit() {
// TODO: Implement goto functionality
}
private void selectAllEdit() {
textArea.selectAll();
}
private void timeDateEdit() {
textArea.insert(new java.util.Date().toString(), textArea.getCaretPosition());
}
private void wordWrapFormat() {
textArea.setLineWrap(!textArea.getLineWrap());
wordWrapFormat.setSelected(textArea.getLineWrap());
}
private void fontFormat() {
// TODO: Implement font selection functionality
}
private void statusBarView() {
statusBar.setVisible(!statusBar.isVisible());
statusBarView.setSelected(statusBar.isVisible());
}
private void aboutHelp() {
JOptionPane.showMessageDialog(this, "Simple Notepad\n\nCreated by Your Name Here", "About Simple Notepad", JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) {
new SimpleNotepad();
}
}
```
这个记事本利用了Java Swing库的许多组件和功能,包括文本区域、滚动窗格、菜单、菜单项、对话框等。它可以打开、保存、打印、撤消、剪切、复制、粘贴和删除文本,还可以查找、替换、跳转、全选、插入时间/日期,以及调整字体和文本包装等。
阅读全文