MainFrame.java
//
private static final long serialVersionUID = 1L;
private UndoManager manager;
private JFileChooser choose;
private File selectedfile;
private JTextArea text;
private java.awt.Container container;
private JMenuBar menuBar;
private JTextField status;
private boolean newPage = false;
// 文件菜单
private JMenu menu;
private JMenuItem newText;
private JMenuItem open;
private JMenuItem save;
private JMenuItem saveAs;
private JMenuItem exit;
// 编辑菜单
private JMenu edit;
private JMenuItem undo;
private JMenuItem cut;
private JMenuItem copy;
private JMenuItem paste;
private JMenuItem delete;
private JMenuItem searchAndReplace;
// 帮助菜单
private JMenu help;
private JMenuItem helpItem;
// 右键菜单
private JPopupMenu right;
private JMenuItem rightUndo;
private JMenuItem rightCut;
private JMenuItem rightCopy;
private JMenuItem rightPaste;
private JMenuItem rightDelete;
private JMenuItem rightClear;
public MainFrame(){
container = getContentPane();
container.setLayout(new BorderLayout(0, -2));
setJTextArea();
setMenuBar();
setFrameAttributes();
setEdit();
setRight();
setHelp();
setTime();
}
private void setFrameAttributes() {
/*********整体外观设置*************/
setTitle("javaNote");
setSize(700, 600);
Dimension frameSize = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage("images/1.png");
setIconImage(img);
}
private void setJTextArea(){
/******JTextArea文本编辑区域的设置***********/
manager = new UndoManager();
text = new JTextArea();
text.setFont(new Font("宋体", Font.PLAIN, 14));
text.getDocument().addUndoableEditListener(manager);
text.setTabSize(2);
text.setSelectedTextColor(Color.WHITE);
text.setSelectionColor(Color.DARK_GRAY);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setCaretColor(Color.BLACK);
text.setMargin(new Insets(3, 10, 3, 7));
text.setDragEnabled(true);
container.add(new JScrollPane(text,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
}
private void setMenuBar(){
/***********文件菜单的设置********************/
menuBar = new JMenuBar();
menu = new JMenu("文件(F)");
menu.setMnemonic('F');
newText = new JMenuItem("新建(N)");
newText.setMnemonic('N');
newText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (selectedfile == null
&& !text.getText().equals("")
&& JOptionPane.showConfirmDialog(container, "是否保存",
"是否保存", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
choose = new JFileChooser();
int state = choose.showSaveDialog(container);
if (state == JFileChooser.APPROVE_OPTION) {
try {
File file = choose.getSelectedFile();
FileWriter os = new FileWriter(file);
os.write(text.getText(), 0, text.getText().length());
os.flush();
file.createNewFile();
os.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(container, "保存文件失败",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
} else if (selectedfile != null
&& JOptionPane.showConfirmDialog(container, "是否保存",
"是否保存", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
try {
FileWriter os = new FileWriter(selectedfile);
os.write(text.getText(), 0, text.getText().length());
os.flush();
os.close();
} catch (IOException e) {
}
}
text.setText("");
newPage = true;
selectedfile = null;
status.setText("");
}
});
open = new JMenuItem("打开(O)");
open.setMnemonic('O');
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (selectedfile != null
&& JOptionPane.showConfirmDialog(container, "是否保存",
"是否保存", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_NO_OPTION) {
try {
FileWriter os = new FileWriter(selectedfile);
os.write(text.getText(), 0, text.getText().length());
os.flush();
os.close();
newPage = false;
} catch (IOException e) {
}
} else if (selectedfile == null
&& !text.getText().equals("")
&& JOptionPane.showConfirmDialog(container, "是否保存",
"是否保存", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_NO_OPTION) {
choose = new JFileChooser();
int state = choose.showSaveDialog(container);
if (state == JFileChooser.APPROVE_OPTION) {
try {
File file = choose.getSelectedFile();
FileWriter os = new FileWriter(file);
os.write(text.getText(), 0, text.getText().length());
os.flush();
file.createNewFile();
os.close();
newPage = false;
} catch (IOException e) {
JOptionPane.showMessageDialog(container, "保存文件失败",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
choose = new JFileChooser();
choose.setFileFilter(new FilterOperate());
int state = choose.showOpenDialog(container);
if (state == JFileChooser.APPROVE_OPTION) {
status.setText(choose.getSelectedFile().toString());
try {
selectedfile = choose.getSelectedFile();
FileReader isr = new FileReader(selectedfile);
text.read(isr, "");
isr.close();
newPage = false;
} catch (IOException e) {
JOptionPane.showMessageDialog(container, "打开文件失败",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
});
save = new JMenuItem("保存(S)");
save.setMnemonic('S');
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (newPage == true || selectedfile == null) {
choose = new JFileChooser();
int state = choose.showSaveDialog(container);
if (state == JFileChooser.APPROVE_OPTION) {
try {
File file = choose.getSelectedFile();
FileWriter os = new FileWriter(file);
os.write(text.getText(), 0, text.getText().length());
os.flush();
file.createNewFile();
os.close();
newPage = false;
} catch (IOException e) {
JOptionPane.showMessageDialog(container, "保存文件失败",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
} else if (newPage == false && selectedfile != null) {
try {
FileWriter os = new FileWriter(selectedfile);
os.write(text.getText(), 0, text.getText().length());
os.flush();
os.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(container, "保存文件失败",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
});
saveAs = new JMenuItem("另存为(A)");
saveAs.setMnemonic('A');
saveAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
choose = new JFileChooser();
int state = choose.showSaveDialog(container);
if (state == JFileChooser.APPROVE_OPTION) {
try {
File file = choose.getSelectedFile();
FileWriter os = new FileWriter(file);
os.write(text.getText(), 0, text.getText().length());
os.flush();
file.createNewFile();
os.close();
newPage = false;
} catch (IOException e) {
JOptionPane.showMessageDialog(container, "保存文件失败",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
});
exit = new JMenuItem("退出(Q)");
exit.setMnemonic('Q');
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menu.add(newText);
menu.add(open);
menu.add(save);
menu.add(saveAs);
menu.add(exit);
menuBar.add(menu);
status = new JTextField(1);
status.setText("wangjian 2013/9/3/night ");
status.setEditable(false);
container.add(status, BorderLayout.SOUTH);
container.add(menuBar, BorderLayout.NORTH);
}
private void setEdit(){
/**************编辑菜单***********************/
edit = new JMenu("编辑(E)");
edit.setMnemonic('E');
undo = new JMenuItem("撤销(U)");
undo.setMnemonic('U');
undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (manager.canUndo())
manager.undo();
}
});
cut = new JMenuItem("剪切(X)");
cut.setMnemonic('X');
cut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.cut();
}
});
copy = new JMenuItem("复制(C)");
copy.setMnemonic('C');
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.copy();
}
});
paste = new JMenuItem("粘贴(V)");
paste.setMnemonic('V');
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.paste();
}
});
delete = new JMenuItem("删除(D)");
delete.setMnemonic('D');
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.replaceRange("", text.getSelectionStart(),
text.getSelectionEnd());
}
});
searchAndReplace = new JMenuItem("查找与替换(M)");
searchAndReplace.setMnemonic('M');
searchAndReplace.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
new SearchOperate();
}
});
edit.add(undo);
edit.addSeparator();
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(delete);
edit.addSeparator();
edit.add(searchAndReplace);
menuBar.add(edit);
}
private void setRight(){
/**************右键菜单设置*******************/
right = new JPopupMenu();
rightUndo = new JMenuItem("撤销");
rightUndo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (manager.canUndo())
manager.undo();
}
});
rightCut = new JMenuItem("剪切");
rightCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.cut();
}
});
rightCopy = new JMenuItem("复制");
rightCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.copy();
}
});
rightPaste = new JMenuItem("粘贴");
rightPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.paste();
}
});
rightDelete = new JMenuItem("删除");
rightDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.replaceRange("", text.getSelectionStart(),
text.getSelectionEnd());
}
});
rightClear = new JMenuItem("清空");
rightClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
text.setText("");
}
});
right.add(rightUndo);
right.add(rightCut);
right.add(rightCopy);
right.addSeparator();
right.add(rightPaste);
right.add(rightDelete);
right.add(rightClear);
text.add(right);
text.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
if (event.isPopupTrigger()) {
right.setVisible(true);
right.show(text, event.getX(), event.getY());
}
}
});
}
private void setHelp(){
/**************设置帮助菜单********************/
help = new JMenu("帮助(H)");
help.setMnemonic('H');
helpItem = new JMenuItem("使用帮助");
helpItem.setMnemonic('P');
helpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
InputEvent.CTRL_MASK));
helpItem.addActionListener(new SystemHelpAction(this));
help.add(helpItem);
menuBar.add(help);
}
private void setTime(){
final JMenu stateBar = new JMenu();
stateBar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
new java.util.Timer().scheduleAtFixedRate(
new TimerTask(){
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
public void run() {
stateBar.setText("" + df.format(new Date()) + " ");
}
}, 0, 1000);
JMenuItem time = new JMenuItem(" 当前系统时间 ");
time.toString();
stateBar.add(time);
menuBar.add(stateBar);
}
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
@SuppressWarnings("unused")
MainFrame mf = new MainFrame();
}
public class SearchOperate extends JFrame{
private static final long serialVersionUID = 1L;
private JTabbedPane tab;
private Container cont;
// 查找
private JPanel searPanel;
private JTextField searField;
private JButton searButton;
// 替换
private JPanel replPanel;
private JPanel buttonPanel;
private JTextField replField;
private JButton replButton;
private JLabel label;
private JTextField replSear;
MainFrame mfe;
public SearchOperate() {
super("查找与替换");
cont = getContentPane();
tab = new JTabbedPane(JTabbedPane.TOP);
// 查找
searPanel = new JPanel(new FlowLayout());
searField = new JTextField(15);
searButton = new JButton("查找下一处");
searPanel.add(searField);
searPanel.add(searButton);
searButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String searText = searField.getText().trim();
if (searText.equals("")) {
JOptionPane.showMessageDialog(cont, "查找串为空", "提示信息",
JOptionPane.INFORMATION_MESSAGE);
} else {
String allText = text.getText();
int start = allText.indexOf(searText,
text.getSelectionEnd());
if (start == -1)
JOptionPane.showMessageDialog(container,
"已到达文件末尾,没有找到\n" + searText, "提示信息",
JOptionPane.INFORMATION_MESSAGE);
else
text.select(start, start + searText.length());
}
}
});
// 替换
replPanel = new JPanel(new GridLayout(3, 1));
buttonPanel = new JPanel(new FlowLayout());
label = new JLabel("替换为");
replField = new JTextField(15);
replSear = new JTextField(15);
replButton = new JButton("替换下一处");
replButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String searText = replSear.getText();
if (searText.equals("")) {
JOptionPane.showMessageDialog(cont, "要替换的串为空", "提示信息",
JOptionPane.INFORMATION_MESSAGE);
} else {
String allText = text.getText();
int start = allText.indexOf(searText,
text.getSelectionEnd());
if (start == -1)
JOptionPane.showMessageDialog(container, "替换完毕",
"提示信息", JOptionPane.INFORMATION_MESSAGE);
else
text.replaceRange(replField.getText(), start, start
+ searText.length());
}
}
});
replPanel.add(replSear);
replPanel.add(label);
replPanel.add(replField);
buttonPanel.add(replButton);
JPanel panel = new JPanel(new FlowLayout());
panel.add(replPanel);
panel.add(buttonPanel);
tab.addTab("查找", searPanel);
tab.addTab("替换", panel);
tab.setVisible(true);
cont.add(tab);
pack();
Point paraLoca = container.getLocationOnScreen();
setLocation(paraLoca.y + getSize().width-5, paraLoca.x
+ getSize().height-5);
setVisible(true);
setResizable(false);
addWindowListener(new WindowAdapter() {
@SuppressWarnings("unused")
public void windowClosing() {
dispose();
}
});
}
}
}
FilterOperate.java
//
public class FilterOperate extends javax.swing.filechooser.FileFilter{
public boolean accept(File file) {
String name = file.getName().toLowerCase();
if (name.endsWith(".txt") || name.endsWith(".cmd")
|| file.isDirectory() || name.endsWith(".sql")
|| name.endsWith(".properties") || name.endsWith(".java")
|| name.endsWith(".cpp") || name.endsWith(".c")
|| name.endsWith(".css") || name.endsWith(".js")
|| name.endsWith(".xml") || name.endsWith(".html")
|| name.endsWith(".log"))
return true;
else
return false;
}
public String getDescription() {
return ".txt | .cmd | .sql |.properties | .java | .cpp | .c | .css | .js | .xml | .html |.log";
}
}
helpdialog.java
//
public class HelpDialog extends JPanel{
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private JDialog dialog = null;
public HelpDialog(){
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setColor.lightGray);
add(new JScrollPane(textArea), BorderLayout.CENTER);
try {
File f = new File("images/");
Scanner in = new Scanner(f);
while (in.hasNext()) {
textArea.append(in.nextLine() + "\n");
}
} catch (IOException e) {
textArea.append("\n由于时间已晚,记事本还有许多地方有待完善和改进,\n" +
"随心所做,只是实现了记事本的大体功能,\n" +
"并没有过多考虑代码的美观,规范,简洁和健壮性...\n" +
"在实现查找替功能时,请将鼠标定位到所要查找字符的至少前一位\n" +
"点击鼠标右键快捷操作\n"+
"诸多不足,请多谅解,指正。\n2013.9.3 night. ");
}
}
public void showDialog(Component parent) {
Frame owner = null;
if (parent instanceof Frame)
owner = (Frame) parent;
else
owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class,
parent);
if (dialog == null || dialog.getOwner() != owner) {
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.pack();
}
dialog.setTitle("系统帮助");
dialog.setSize(400, 450);
// set the Location of this dialog to the center
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension size = kit.getScreenSize();
int width = size.width;
int height = size.height;
dialog.setLocation((width - dialog.getWidth()) / 2, (height - dialog
.getHeight()) / 2);
dialog.setVisible(true);
}
}
本文出自 “java记事本” 博客,转载请与作者联系!