转自:http://blog.sina.com.cn/s/blog_666c46fb0100kw3v.html
Java记事本源代码,总共有三步。
第一步:建一个新类,名字是kk。kk.java的源代码如下所示:
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.File;
public class kk extends Frame implements ActionListener{
final FontChooser fontChooser1 = new FontChooser(kk.this);
//FontPicker fontChooser1=new FontPicker();
TextArea textarea=new TextArea();
MenuBar menubar=new MenuBar();
Menu filemenu=new Menu("文件");
MenuItem newitem=new MenuItem("新建");
MenuItem openitem=new MenuItem("打开");
MenuItem saveasitem=new MenuItem("保存");
MenuItem exititem=new MenuItem("退出");
Menu editmenu=new Menu("编辑");
MenuItem selectitem=new MenuItem("全选");
MenuItem copyitem=new MenuItem("复制");
MenuItem cutitem=new MenuItem("剪切");
MenuItem pasteitem=new MenuItem("粘贴");
Menu wordmenu=new Menu("字体");
MenuItem qianitem=new MenuItem("设置前景色");
MenuItem beiitem=new MenuItem("设置背景色");
MenuItem ziitem=new MenuItem("字体格式");
Menu aboutmenu=new Menu("关于");
MenuItem info=new MenuItem("关于记事本");
JToolBar toolBar=new JToolBar();
ImageIcon leftButtonIcon=new ImageIcon("new.gif");
ImageIcon middleButtonIcon=new ImageIcon("open.gif");
ImageIcon rightButtonIcon=new ImageIcon("save.gif");
ImageIcon copyButtonIcon=new ImageIcon("copy.gif");
ImageIcon cutButtonIcon=new ImageIcon("cut.gif");
ImageIcon pasteButtonIcon=new ImageIcon("paste.gif");
JButton jb1=new JButton("新建(N)",leftButtonIcon);
JButton jb2=new JButton("打开(O)",middleButtonIcon);
JButton jb3=new JButton("保存(S)",rightButtonIcon);
JButton jb4=new JButton("复制(C)",copyButtonIcon);
JButton jb5=new JButton("剪切(X)",cutButtonIcon);
JButton jb6=new JButton("粘贴(V)",pasteButtonIcon);
String fileName="NoName";
Toolkit toolkit=Toolkit.getDefaultToolkit();
Clipboard clipboard=toolkit.getSystemClipboard();
private FileDialog openFileDialog=new FileDialog(this,"打开文
件",FileDialog.LOAD);
private FileDialog saveAsFileDialog=new FileDialog(this,"保存文
件",FileDialog.SAVE);
public kk(){
setTitle("记事本");
setFont(new Font("Times New Roman",Font.PLAIN,20));
setBackground(Color.white);
setSize(800,600);
setLocation(100,100);
jb1.setToolTipText("新建文件,快捷键Alt+N");
jb2.setToolTipText("打开文件,快捷键Alt+O");
jb3.setToolTipText("保存文件,快捷键Alt+S");
jb4.setToolTipText("复制文件,快捷键Alt+C");
jb5.setToolTipText("剪切文件,快捷键Alt+X");
jb6.setToolTipText("粘贴文件,快捷键Alt+V");
// jb1.setVerticalTextPosition(AbstractButton.CENTER);//水平中间对齐
// jb1.setHorizontalTextPosition(AbstractButton.LEADING);//相当于LEFT
filemenu.add(newitem);
filemenu.add(openitem);
filemenu.addSeparator();
filemenu.add(saveasitem);
filemenu.addSeparator();
filemenu.add(exititem);
// filemenu.setMnemonic('F');
editmenu.add(selectitem);
editmenu.add(copyitem);
editmenu.addSeparator();
editmenu.add(cutitem);
editmenu.add(pasteitem);
wordmenu.add(qianitem);
wordmenu.add(beiitem);
wordmenu.addSeparator();
wordmenu.add(ziitem);
toolBar.add(jb1);
toolBar.add(jb2);
toolBar.add(jb3);
toolBar.add(jb4);
toolBar.add(jb5);
toolBar.add(jb6);
menubar.add(filemenu);
menubar.add(editmenu);
menubar.add(wordmenu);
menubar.add(aboutmenu);
aboutmenu.add(info);
setMenuBar(menubar);
// setMenuBar(menubar);
setLayout(new BorderLayout());
add(textarea,BorderLayout.CENTER);
add(toolBar,BorderLayout.NORTH);
addWindowListener(new WindowAdapter(){public void windowClosing
(WindowEvent e){System.exit(0);}});
newitem.addActionListener(this);
openitem.addActionListener(this);
saveasitem.addActionListener(this);
exititem.addActionListener(this);
selectitem.addActionListener(this);
copyitem.addActionListener(this);
cutitem.addActionListener(this);
pasteitem.addActionListener(this);
info.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
jb3.addActionListener(this);
jb4.addActionListener(this);
jb5.addActionListener(this);
jb6.addActionListener(this);
jb1.setMnemonic(KeyEvent.VK_N);
jb2.setMnemonic(KeyEvent.VK_O);
jb3.setMnemonic(KeyEvent.VK_S);
jb4.setMnemonic(KeyEvent.VK_C);
jb5.setMnemonic(KeyEvent.VK_X);
jb6.setMnemonic(KeyEvent.VK_V);
qianitem.addActionListener(this);
beiitem.addActionListener(this);
ziitem.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
Object eventSource=e.getSource();
if(eventSource==newitem){
textarea.setText("");
}else if(eventSource==openitem){
openFileDialog.show();
fileName=openFileDialog.getDirectory()+openFileDialog.getFile();
if(fileName!=null)
readFile(fileName);
}
else if(eventSource==saveasitem){
saveAsFileDialog.show();
fileName=saveAsFileDialog.getDirectory()+saveAsFileDialog.getFile();
if(fileName!=null)
writeFile(fileName);
}
else if(eventSource==selectitem){
textarea.selectAll();
}
else if(eventSource==copyitem){
String text = textarea.getSelectedText();
StringSelection selection= new StringSelection(text);
clipboard.setContents(selection,null);
}
else if(eventSource==cutitem){
String text=textarea.getSelectedText();
StringSelection selection=new StringSelection(text);
clipboard.setContents(selection, null);
textarea.replaceRange("",textarea.getSelectionStart
(),textarea.getSelectionEnd());
}else if(eventSource==pasteitem){
Transferable contents=clipboard.getContents(this);
if(contents==null)
return;
String text;
text="";
try{text=(String) contents.getTransferData
(DataFlavor.stringFlavor);}catch (Exception exception){
}textarea.replaceRange(text, textarea.getSelectionStart
(),textarea.getSelectionEnd() );
}else if(eventSource==exititem)
{
// System.exit(0);
Object[] options = { "是","否", "取消" };
int s = JOptionPane.showOptionDialog(null, "按“否”后,直接退出记
事本,文档将会消失,无法恢复。" +
"\n按“是”后,进行保存文档操作。保存完毕后,自动退出记事本,程
序结束运行。\n按”取消“后,返回记事本继续编辑。", "警告!请注意保存文
档!",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[0]);
if (s == JOptionPane.YES_OPTION)
{
saveAsFileDialog.show();
fileName=saveAsFileDialog.getDirectory()+saveAsFileDialog.getFile
();
if(fileName!=null){
writeFile(fileName);
}
System.exit(0);
}
else if (s == JOptionPane.NO_OPTION)
{
System.exit(0);
}
}
// {
//// System.exit(0);
//
// Object[] options = { "确定", "取消" };
// int s = JOptionPane.showOptionDialog(null, "按“确定”后,退出记
事本,文档将会消失,无法恢复。" +
// "\n按“取消”后,进行保存文档操作。\n保存完毕后,自动退出记事
本,程序结束运行。", "警告!请注意保存文档!",
// JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
// options, options[0]);
// if (s == JOptionPane.YES_OPTION)
// {
// System.exit(0);
// }
// else if (s == JOptionPane.NO_OPTION)
// {
// saveAsFileDialog.show();
// fileName=saveAsFileDialog.getDirectory()
+saveAsFileDialog.getFile();
// if(fileName!=null){
// writeFile(fileName);
// }
// System.exit(0);
// }
// }
else if(eventSource==info){
// Icon help_icon = new ImageIcon("doit.jpg");
// String help = "DOIT(R)记事本\n版本1.0 (内部版本号
2008.xp_sp2_dave.080423-10)\n版权"
// + "所有 (C) 2008-2008 DOIT。\n最终解释权归本人所有,"
// + "授权给:\n\nBuild By Davezhang\nQQ:442803117
\nBolg:http://hi.baidu.com.442803117"
// + "\nEmail:442803117@qq.com";
// JOptionPane.showConfirmDialog(null, help, "帮助",
// JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
// help_icon);
Icon help_icon = new ImageIcon("doit.jpg");
String help = "感谢您的使用!\n本记事本程序暂无帮助,您可以参考
WindowsXP的记事本帮助程序!\n"
+ "欢迎和作者联系交流!\n"
+ "Build By HaoPenghua\nQQ:1013795885\nBolg:http://hi.baidu.com/
郝鹏华"
+ "\nEmail:1013795885@qq.com";
JOptionPane.showConfirmDialog(null, help, "关于记事本",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
help_icon);
// JOptionPane.showMessageDialog(null,"本软件是一个小的记事本,欢迎大
家使用!" );//显示信息对话框
}
else if(eventSource==qianitem){
Color color=JColorChooser.showDialog(this,"前景
色",textarea.getForeground());
if(color!=null){
textarea.setForeground(color);
}
}
else if(eventSource==beiitem){
Color color=JColorChooser.showDialog(this,"背景
色",textarea.getBackground());
if(color!=null){
textarea.setBackground(color);
}
}
else if(eventSource==ziitem){
fontChooser1.setVisible(true);
// If we got a real font choice, then update our go button
if (fontChooser1.getNewFont() != null) {
textarea.setFont(fontChooser1.getNewFont());
textarea.setForeground(fontChooser1.getNewColor());
}
// fontChooser1=new FontPicker();
fontChooser1.show();
// fontChooser1.setSelectedFont(textarea.getFont());
// if(fontChooser1.showDialog()){
// Font font=fontChooser1.setSelectedFont(font);
// textarea.setFont(font);
// }
// this.repaint();
// textarea.repaint();
}
else if(eventSource==jb1){
textarea.setText("");
}
else if(eventSource==jb2){
openFileDialog.show();
fileName=openFileDialog.getDirectory()+openFileDialog.getFile();
if(fileName!=null)
readFile(fileName);
}
else if(eventSource==jb3){
saveAsFileDialog.show();
fileName=saveAsFileDialog.getDirectory()+saveAsFileDialog.getFile();
if(fileName!=null)
writeFile(fileName);
}
else if(eventSource==jb4){
String text = textarea.getSelectedText();
StringSelection selection= new StringSelection(text);
clipboard.setContents(selection,null);
}
else if(eventSource==jb5){
String text=textarea.getSelectedText();
StringSelection selection=new StringSelection(text);
clipboard.setContents(selection, null);
textarea.replaceRange("",textarea.getSelectionStart
(),textarea.getSelectionEnd());
}
else if(eventSource==jb6){
Transferable contents=clipboard.getContents(this);
if(contents==null)
return;
String text;
text="";
try{text=(String) contents.getTransferData
(DataFlavor.stringFlavor);}catch (Exception exception){
}textarea.replaceRange(text, textarea.getSelectionStart
(),textarea.getSelectionEnd() );
}
}
public void readFile(String fileName){
try{
File file=new File(fileName);
FileReader readIn=new FileReader(file);
int size=(int) file.length();
int charsRead=0;
char[] content=new char[size];
while(readIn.ready())
charsRead+=readIn.read(content,charsRead,size-charsRead);
readIn.close();
textarea.setText(new String(content,0,charsRead));
}catch (IOException e){
System.out.println("Error Opening file");
}
}
public void writeFile(String fileName){
try{
File file=new File(fileName);
FileWriter writeOut=new FileWriter(file);
writeOut.write(textarea.getText());
writeOut.close();
}catch (IOException e){
System.out.println("Error writing file");
}
}
public static void main(String[] args){
kk frame=new kk();
frame.show();
}
}
第二步:再建一个新类,名字是FontPicker。FontPicker.java和kk.java必须在
同一目录下,FontPicker.java的源代码如下所示:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class FontPicker extends JFrame {
Color c;
public FontPicker() {
super("JColorChooser Test Frame");
setSize(200, 100);
final JButton go = new JButton("Show FontChooser");
go.addActionListener(new ActionListener() {
final FontChooser chooser = new FontChooser(FontPicker.this);
boolean first = true;
public void actionPerformed(ActionEvent e) {
chooser.setVisible(true);
// If we got a real font choice, then update our go button
if (chooser.getNewFont() != null) {
go.setFont(chooser.getNewFont());
go.setForeground(chooser.getNewColor());
}
}
});
getContentPane().add(go);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String args[]) {
FontPicker fp = new FontPicker();
fp.setVisible(true);
}
}
//FontChooser.java
//A font chooser that allows users to pick a font by name, size, style,
and
//color. The color selection is provided by a JColorChooser pane. This
//dialog builds an AttributeSet suitable for use with JTextPane.
//
class FontChooser extends JDialog implements ActionListener {
JColorChooser colorChooser;
JComboBox fontName;
JCheckBox fontBold, fontItalic;
JTextField fontSize;
JLabel previewLabel;
SimpleAttributeSet attributes;
Font newFont;
Color newColor;
public FontChooser(Frame parent) {
super(parent, "字体格式", true);
setSize(450, 450);
attributes = new SimpleAttributeSet();
// Make sure that any way the user cancels the window does the
right
// thing
// addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e) {
// closeAndCancel();
// }
// });
// Start the long process of setting up our interface
Container c = getContentPane();
JPanel fontPanel = new JPanel();
fontName = new JComboBox(new String[] { "TimesRoman", "Helvetica",
"Courier" });
fontName.setSelectedIndex(1);
fontName.addActionListener(this);
fontSize = new JTextField("12", 4);
fontSize.setHorizontalAlignment(SwingConstants.RIGHT);
fontSize.addActionListener(this);
fontBold = new JCheckBox("Bold");
fontBold.setSelected(true);
fontBold.addActionListener(this);
fontItalic = new JCheckBox("Italic");
fontItalic.addActionListener(this);
fontPanel.add(fontName);
fontPanel.add(new JLabel(" Size: "));
fontPanel.add(fontSize);
fontPanel.add(fontBold);
fontPanel.add(fontItalic);
c.add(fontPanel, BorderLayout.NORTH);
// Set up the color chooser panel and attach a change listener so
that
// color
// updates get reflected in our preview label.
colorChooser = new JColorChooser(Color.black);
colorChooser.getSelectionModel().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
updatePreviewColor();
}
});
c.add(colorChooser, BorderLayout.CENTER);
JPanel previewPanel = new JPanel(new BorderLayout());
previewLabel = new JLabel("Here's a sample of this font.");
previewLabel.setForeground(colorChooser.getColor());
previewPanel.add(previewLabel, BorderLayout.CENTER);
// Add in the Ok and Cancel buttons for our dialog box
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
closeAndSave();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
closeAndCancel();
}
});
JPanel controlPanel = new JPanel();
controlPanel.add(okButton);
controlPanel.add(cancelButton);
previewPanel.add(controlPanel, BorderLayout.SOUTH);
// Give the preview label room to grow.
previewPanel.setMinimumSize(new Dimension(100, 100));
previewPanel.setPreferredSize(new Dimension(100, 100));
c.add(previewPanel, BorderLayout.SOUTH);
}
// Ok, something in the font changed, so figure that out and make a
// new font for the preview label
public void actionPerformed(ActionEvent ae) {
// Check the name of the font
if (!StyleConstants.getFontFamily(attributes).equals(
fontName.getSelectedItem())) {
StyleConstants.setFontFamily(attributes, (String) fontName
.getSelectedItem());
}
// Check the font size (no error checking yet)
if (StyleConstants.getFontSize(attributes) != Integer.parseInt
(fontSize
.getText())) {
StyleConstants.setFontSize(attributes, Integer.parseInt(fontSize
.getText()));
}
// Check to see if the font should be bold
if (StyleConstants.isBold(attributes) != fontBold.isSelected()) {
StyleConstants.setBold(attributes, fontBold.isSelected());
}
// Check to see if the font should be italic
if (StyleConstants.isItalic(attributes) != fontItalic.isSelected())
{
StyleConstants.setItalic(attributes, fontItalic.isSelected());
}
// and update our preview label
updatePreviewFont();
}
// Get the appropriate font from our attributes object and update
// the preview label
protected void updatePreviewFont() {
String name = StyleConstants.getFontFamily(attributes);
boolean bold = StyleConstants.isBold(attributes);
boolean ital = StyleConstants.isItalic(attributes);
int size = StyleConstants.getFontSize(attributes);
//Bold and italic don't work properly in beta 4.
Font f = new Font(name, (bold ? Font.BOLD : 0)
+ (ital ? Font.ITALIC : 0), size);
previewLabel.setFont(f);
}
// Get the appropriate color from our chooser and update previewLabel
protected void updatePreviewColor() {
previewLabel.setForeground(colorChooser.getColor());
// Manually force the label to repaint
previewLabel.repaint();
}
public Font getNewFont() {
return newFont;
}
public Color getNewColor() {
return newColor;
}
public AttributeSet getAttributes() {
return attributes;
}
public void closeAndSave() {
// Save font & color information
newFont = previewLabel.getFont();
newColor = previewLabel.getForeground();
// Close the window
setVisible(false);
}
public void closeAndCancel() {
// Erase any font information and then close the window
newFont = null;
newColor = null;
setVisible(false);
}
public Font setSelectedFont(Font font) {
JTextArea textarea=null;
// TODO 自动生成方法存根
return textarea.getFont();
}
}
第三步:本项目需要用到7张图片,这7张图片就在下面,从上到下分别为copy.gif、cut.gif、new.gif、
open.gif、paste.gif、save.gif、doit.jpg,这7张图片必须要和kk.class和
FontPicker.class放在同一目录下。最后编译运行成功。
附图:“项目运行成功后的情况”的图示:
相关推荐
java记事本 源代码下载 java记事本 源代码下载 java记事本 源代码下载 java记事本 源代码下载
* 此为一个java记事本的源代码 * 此记事本的主要功能: * 1、对文本文件进行打开,编辑,修改,保存,另存为 等基本操作 * 2、能够对文本中文字字体、字形、字号进行设置,及其信息的保存与恢复 * 3、能够...
记事本源代码 记事本源代码 记事本源代码
java记事本+源程序 初步学完java在老师和同学的帮助下完成初学者可以参考相互学习
日历记事本Java源代码,很值得一看哟。
Java记事本程序源代码 Java记事本程序源代码 Java记事本程序源代码
java 记事本 源代码 swing java 记事本 源代码 swing java 记事本 源代码 swing java 记事本 源代码 swing java 记事本 源代码 swing
该程序是用myeclipse 自己编的 可以实现修改 字体大小颜色 保存,复制 粘贴,剪切 添加系统时间 可以打开 txt文件,功能还算可以 一部分代码是抄袭的 不是原创,
Java编写记事本的源代码,包括工具栏、菜单栏、状态栏,以及基本功能的实现。
JAVA记事本程序可以说是对JAVA的一次综合,这是我的JAVA老师自已编出来为了方便教学之用,这个程序的功能和WINDOWS操作系统自帶的记事本程序一样。
用java写的记事本,功能和win7自带记事本相当,而且完全按照win7自带记事本来写的,甚至连外观都一样,任何初学java的人都值得看一下
Java源码,记事本
JAVA记事本+源代码.rar
Java记事本程序源代码.pdf
JAVA记事本程序源代码