java记事本课程源代码 记事本编写java程序-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

java记事本课程源代码 记事本编写java程序

记事本JAVA的源代码

import java.awt.BorderLayout;

成都创新互联专注于企业成都全网营销推广、网站重做改版、西市网站定制设计、自适应品牌网站建设、html5商城网站建设、集团公司官网建设、外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为西市等各大城市提供网站开发制作服务。

import java.awt.FileDialog;

import java.awt.Font;

import java.awt.datatransfer.Clipboard;

import java.awt.datatransfer.DataFlavor;

import java.awt.datatransfer.StringSelection;

import java.awt.datatransfer.Transferable;

import java.awt.datatransfer.UnsupportedFlavorException;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.border.TitledBorder;

/*因为根据个人的电脑路径可能有所偏差,没有源路径的情况下,设置默认保存路径为D盘根目录下

* 若要选择保存其他地方,可以选择 另存为*/

public class TestDemo extends JFrame {

private static final long serialVersionUID = -5355432125621015300L;

private String url = null;//文件路径

private String str=null;//复制或剪切 的字符串

private StringSelection stringSelection=null;

private Clipboard clipboard=new Clipboard(str);

private Transferable transferable=null;

private DataFlavor flavor=null;

public TestDemo() {

init();

}

private void init() {

setTitle("我的记事本");

setSize(500, 600);

setContentPane(createContentPane());//添加主面板

}

/*创建主面板*/

private JPanel createContentPane() {

JPanel pane = new JPanel(new BorderLayout());

pane.add(BorderLayout.NORTH, createChocePane());//添加菜单栏

pane.add(createAreaPane());//添加文本编辑区域

return pane;

}

/*创建菜单栏,以及实现功能*/

private JPanel createChocePane() {

JPanel pane = new JPanel();

JMenuBar menuBar1 = new JMenuBar();

JMenu menu = new JMenu("文件");

menuBar1.add(menu);

JMenuItem menuIt1 = new JMenuItem("新建");

JMenuItem menuIt2 = new JMenuItem("打开");

JMenuItem menuIt3 = new JMenuItem("保存");

JMenuItem menuIt4 = new JMenuItem("另存为");

menu.add(menuIt1);

menu.add(menuIt2);

menu.add(menuIt3);

menu.add(menuIt4);

JMenuBar menuBar2 = new JMenuBar();

JMenu menu2 = new JMenu("编辑");

menuBar2.add(menu2);

JMenuItem menuIt5 = new JMenuItem("复制");

JMenuItem menuIt6 = new JMenuItem("剪切");

JMenuItem menuIt7 = new JMenuItem("粘帖");

menu2.add(menuIt5);

menu2.add(menuIt6);

menu2.add(menuIt7);

JMenuBar menuBar3 = new JMenuBar();

JMenu menu3 = new JMenu("帮助");

menuBar3.add(menu3);

JMenuItem menuIt8 = new JMenuItem("关于记事本");

menu3.add(menuIt8);

pane.add(menuBar1);

pane.add(menuBar2);

pane.add(menuBar3);

menuIt1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

testArea.setText(null);

}

});

menuIt2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

final FileDialog fd = new FileDialog(new JFrame(), "查找文件",

FileDialog.LOAD);

fd.setVisible(true);

if (fd.getDirectory() != null fd.getFile() != null) {

testArea.setText(null);

url = fd.getDirectory() + fd.getFile();

try {

BufferedReader in = new BufferedReader(new FileReader(

url));

for (int i = 0;; i++) {

testArea.append(in.readLine());

if (in.read() == -1) {

break;

} else

continue;

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

});

menuIt3.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (url==null) {

url="D:\\新建 文本文档.txt";

}

File f = new File(url);

BufferedWriter out = null;

try {

out = new BufferedWriter(new FileWriter(url));

f.createNewFile();

out.append(testArea.getText());

out.flush();

} catch (IOException e1) {

e1.printStackTrace();

} finally {

try {

out.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

});

menuIt4.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

FileDialog fd = new FileDialog(new JFrame(), "保存文本",

FileDialog.SAVE);

fd.setVisible(true);

if (url!=null) {

File f = new File(url);

BufferedWriter out = null;

try {

f.createNewFile();

out = new BufferedWriter(new FileWriter(url));

out.append(testArea.getText());

out.flush();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

});

menuIt5.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

str=testArea.getSelectedText();

stringSelection=new StringSelection(str);

clipboard.setContents(stringSelection, null);

}

});

menuIt6.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

str=testArea.getSelectedText();

stringSelection=new StringSelection(str);

clipboard.setContents(stringSelection, null);

int start=testArea.getSelectionStart();

int end=testArea.getSelectionEnd();

testArea.replaceRange( null,start,end);

}

});

menuIt7.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

transferable=clipboard.getContents(this);

flavor=DataFlavor.stringFlavor;

if (transferable.isDataFlavorSupported(flavor)) {

int start=testArea.getSelectionStart();

int end=testArea.getSelectionEnd();

testArea.replaceRange( null,start,end);

int pos=testArea.getCaretPosition();

try {

str=(String)transferable.getTransferData(flavor);

testArea.insert(str, pos);

} catch (UnsupportedFlavorException e1) {

e1.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

});

menuIt8.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(null,"功能简单,绝对原创 ");

}

});

return pane;

}

JTextArea testArea;

private JScrollPane createAreaPane() {

JScrollPane pane = new JScrollPane();

pane.setBorder(new TitledBorder("编辑区域"));

testArea = new JTextArea();

testArea.setFont(new Font("宋体", Font.BOLD, 13));

testArea.setLineWrap(true);

pane.getViewport().add(testArea);

return pane;

}

public static void main(String[] args) {

TestDemo td = new TestDemo();

td.setVisible(true);

}

}

Java记事本源代码

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.datatransfer.Clipboard;

import java.awt.datatransfer.DataFlavor;

import java.awt.datatransfer.Transferable;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.FocusEvent;

import java.awt.event.FocusListener;

import java.awt.event.InputEvent;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

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.JPanel;

import javax.swing.JPopupMenu;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.KeyStroke;

import javax.swing.filechooser.FileFilter;

public class Demo extends JFrame {

private static final long serialVersionUID = 1L; //Eclipse自动生成序列号

String name = "无标题";

JPanel menuPanel = new JPanel();

JTextArea text = new TextAreaMenu(); //文本编辑区

JScrollPane jsp = new JScrollPane(text); //可滚动编辑区

JMenuBar mnbMain = new JMenuBar();

JMenu mnServer = new JMenu("文件(F)");

JMenu mnEdit = new JMenu("编辑(E)");

JMenuItem[] mniServers = new JMenuItem[]{

new JMenuItem("新建(N)"),

new JMenuItem("保存(S)"),

new JMenuItem("打开(O)"),

new JMenuItem("退出(X)"),

};

{

menuPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));

mnbMain.add(mnServer);

menuPanel.add(mnbMain);

mnbMain.setBounds(5, 0, 50, 30);

for (int i = 0; i mniServers.length; i++) {

mnServer.add(mniServers[i]);

}

mniServers[0].addActionListener(new ActionListener() { //定义"新建"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

new Demo(getLocation().x+15,getLocation().y+5);

}

});

mniServers[1].addActionListener(new ActionListener() { //定义"保存"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

chooseToSave();

}

});

mniServers[2].addActionListener(new ActionListener() { //定义"打开"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

chooseToOpen();

}

});

mniServers[3].addActionListener(new ActionListener() { //定义"退出"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

System.exit(0);

}

});

text.addFocusListener(new FocusListener() {

@Override

public void focusLost(FocusEvent e) {

// TODO Auto-generated method stub

}

@Override

public void focusGained(FocusEvent e) {

}

});

}

public Demo(int x,int y) {

this.setTitle( name +" - 记事本");

this.setBounds(x, y, 600, 400);

this.setLayout(new BorderLayout());

this.add(menuPanel, BorderLayout.NORTH);

this.add(jsp);

jsp.setBounds(5, 30, getWidth()-10, getHeight()-50);

this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

this.setVisible(true);

}

public Demo() {

this(200,200);

}

protected void chooseToSave() {

File file = chooseFile();

if(null==file)return;

if(file.exists()){

int cho = JOptionPane.showConfirmDialog(this, "文件已存在,是否覆盖?");

System.out.println(cho);

if(cho==JOptionPane.OK_OPTION)save(file);

else return;

}

else save(file);

}

private void save(File file) {

name = file.getName();

write(text.getText(),file.getPath());

this.setTitle( name +" - 记事本");

}

protected void chooseToOpen() {

File file = chooseFile();

if(null==file||!file.exists())return;

name = file.getName();

Demo.this.setTitle( name +" - 记事本");

read(text,file);

}

/*********************************************MAIN**************************************************/

public static void main(String[] args) {

new Demo();

}

private File chooseFile(){

JFileChooser chooser = new JFileChooser(); //构建文件选择器

chooser.setFileFilter(new FileFilter() {

@Override

public String getDescription() {

return "文本文件";

}

@Override

public boolean accept(File f) {

String name = f.getName().toLowerCase();

return f.isDirectory() || name.endsWith(".txt")

||name.endsWith(".c") || name.endsWith(".java")

||name.endsWith(".cpp"); //可识别文件

}

});

int result = chooser.showDialog(null, "确定");

if (result==JFileChooser.APPROVE_OPTION) {

File file = chooser.getSelectedFile();

System.out.println(file.getAbsolutePath());

} else {

System.out.println("未选择文件");

}

return chooser.getSelectedFile();

}

public static void read(JTextArea text,File file){ //定义读取文件操作

FileReader fr;

try {

fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

String string = null;

while((string = br.readLine()) != null){

text.append(string+"\n");

}

br.close();

fr.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void write(String txt,String fileName){

FileWriter fw;

try {

fw = new FileWriter(fileName);

BufferedWriter bw = new BufferedWriter(fw);

bw.write(txt);

bw.flush();

bw.close();

fw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

class TextAreaMenu extends JTextArea implements MouseListener {

private static final long serialVersionUID = -2308615404205560110L;

private JPopupMenu pop = null; // 弹出菜单

private JMenuItem selectAll = null,copy = null, paste = null, cut = null, cancel=null; // 功能菜单

public TextAreaMenu() {

super();

init();

}

private void init() {

this.addMouseListener(this);

this.setSelectedTextColor(Color.red);

pop = new JPopupMenu();

pop.add(selectAll = new JMenuItem("全选"));

pop.add(copy = new JMenuItem("复制"));

pop.add(paste = new JMenuItem("粘贴"));

pop.add(cut = new JMenuItem("剪切"));

pop.add(cancel = new JMenuItem("撤销"));

selectAll.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_MASK));

copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));

paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));

cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));

cancel.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_MASK));

copy.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

action(e);

}

});

paste.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

action(e);

}

});

cut.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

action(e);

}

});

this.add(pop);

}

/**

* 菜单动作

* @param e

*/

public void action(ActionEvent e) {

String str = e.getActionCommand();

if (str.equals(selectAll.getText())) { // 全选

this.selectAll();

}

else if (str.equals(copy.getText())) { // 复制

this.copy();

} else if (str.equals(paste.getText())) { // 粘贴

this.paste();

} else if (str.equals(cut.getText())) { // 剪切

this.cut();

}

else if (str.equals(cancel.getText())) { //撤销

this.cut();

}

}

public JPopupMenu getPop() {

return pop;

}

public void setPop(JPopupMenu pop) {

this.pop = pop;

}

/**

* 剪切板中是否有文本数据可供粘贴

*

* @return true为有文本数据

*/

public boolean isClipboardString() {

boolean b = false;

Clipboard clipboard = this.getToolkit().getSystemClipboard();

Transferable content = clipboard.getContents(this);

try {

if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {

b = true;

}

} catch (Exception e) {

}

return b;

}

/**

* 文本组件中是否具备复制的条件

*

* @return true为具备

*/

public boolean isCanCopy() {

boolean b = false;

int start = this.getSelectionStart();

int end = this.getSelectionEnd();

if (start != end)

b = true;

return b;

}

public void mouseClicked(MouseEvent e) {

}

public void mouseEntered(MouseEvent e) {

}

public void mouseExited(MouseEvent e) {

}

public void mousePressed(MouseEvent e) {

if (e.getButton() == MouseEvent.BUTTON3) {

copy.setEnabled(isCanCopy());

paste.setEnabled(isClipboardString());

cut.setEnabled(isCanCopy());

pop.show(this, e.getX(), e.getY());

}

}

public void mouseReleased(MouseEvent e) {

}

}

JAVA记事本的源代码

我给你如下:/*

* WriteBoard.java

*

* Created on 2006年12月19日, 下午7:26

*/

/**

*

* @author LecH.giF

*/

import java.awt.datatransfer.*;

import java.awt.event.*;

import java.awt.*;

import java.io.*;

import java.awt.FileDialog;

public class WriteBoard extends java.awt.Frame {

Clipboard clipboard =null;

FileDialog fc = new FileDialog(this);

/** Creates new form WriteBoard */

public WriteBoard() {

clipboard = getToolkit().getSystemClipboard();

initComponents();

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// editor-fold defaultstate="collapsed" desc=" Generated Code "

private void initComponents() {

textArea1 = new java.awt.TextArea();

menuBar1 = new java.awt.MenuBar();

menu1 = new java.awt.Menu();

menuItem1 = new java.awt.MenuItem();

menuItem2 = new java.awt.MenuItem();

menuItem3 = new java.awt.MenuItem();

menuItem4 = new java.awt.MenuItem();

menuItem5 = new java.awt.MenuItem();

menu2 = new java.awt.Menu();

menuItem6 = new java.awt.MenuItem();

menuItem7 = new java.awt.MenuItem();

menuItem8 = new java.awt.MenuItem();

setTitle("WriteBoard");

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent evt) {

exitForm(evt);

}

});

add(textArea1, java.awt.BorderLayout.CENTER);

menu1.setLabel("Menu");

menuItem1.setLabel("\u65b0\u5efa");

menuItem1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

newText(evt);

}

});

menu1.add(menuItem1);

menuItem2.setLabel("\u6253\u5f00");

menuItem2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

open(evt);

}

});

menu1.add(menuItem2);

menuItem3.setLabel("\u4fdd\u5b58");

menuItem3.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

menuItem3ActionPerformed(evt);

}

});

menu1.add(menuItem3);

menuItem4.setLabel("\u53e6\u5b58\u4e3a");

menuItem4.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

menuItem4ActionPerformed(evt);

}

});

menu1.add(menuItem4);

menuItem5.setLabel("\u9000\u51fa");

menuItem5.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

exit(evt);

}

});

menu1.add(menuItem5);

menuBar1.add(menu1);

menu2.setLabel("\u7f16\u8f91");

menuItem6.setLabel("\u526a\u5207");

menuItem6.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

menuItem6ActionPerformed(evt);

}

});

menu2.add(menuItem6);

menuItem7.setLabel("\u590d\u5236");

menuItem7.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

menuItem7ActionPerformed(evt);

}

});

menu2.add(menuItem7);

menuItem8.setLabel("\u7c98\u8d34");

menuItem8.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

menuItem8ActionPerformed(evt);

}

});

menu2.add(menuItem8);

menuBar1.add(menu2);

setMenuBar(menuBar1);

pack();

}// /editor-fold

private void menuItem4ActionPerformed(java.awt.event.ActionEvent evt) {

fc.show();

if(fc.getFile()!=null){

File file = new File(fc.getFile());

try {

PrintWriter pw = new PrintWriter(file);

pw.print(textArea1.getText());

pw.flush();

pw.close();

} catch (FileNotFoundException ex) {

ex.printStackTrace();

}

}

else{

return;

}

}

private void menuItem3ActionPerformed(java.awt.event.ActionEvent evt) {

fc.show();

if(fc.getFile()!=null){

File file = new File(fc.getFile());

try {

PrintWriter pw = new PrintWriter(file);

pw.print(textArea1.getText());

pw.flush();

pw.close();

} catch (FileNotFoundException ex) {

ex.printStackTrace();

}

}

else{

return;

}

}

private void menuItem8ActionPerformed(java.awt.event.ActionEvent evt) {

Transferable contents = clipboard.getContents(this);

DataFlavor flavor = DataFlavor.stringFlavor;

if(contents.isDataFlavorSupported(flavor))

try{

String str;

str=(String)contents.getTransferData(flavor);

textArea1.append(str);

}catch(Exception e){}

}

private void menuItem7ActionPerformed(java.awt.event.ActionEvent evt) {

String temp = this.textArea1.getSelectedText();

StringSelection text = new StringSelection(temp);

clipboard.setContents(text,null);

}

private void menuItem6ActionPerformed(java.awt.event.ActionEvent evt) {

String temp = this.textArea1.getSelectedText();

StringSelection text = new StringSelection(temp);

clipboard.setContents(text,null);

int start = textArea1.getSelectionStart();

int end = textArea1.getSelectionEnd();

textArea1.replaceRange("",start,end);

}

private void open(java.awt.event.ActionEvent evt) {

fc.show();

if(fc.getFile()!=null){

File file = new File(fc.getFile());

try {

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

String s;

try {

while((s= br.readLine())!=null){

textArea1.append(s+"\n");

}

fr.close();

br.close();

} catch (IOException ex) {

ex.printStackTrace();

}

} catch (FileNotFoundException ex) {

ex.printStackTrace();

}

}

else{

return;

}

}

private void newText(java.awt.event.ActionEvent evt) {

this.textArea1.setText("");

}

private void exit(java.awt.event.ActionEvent evt) {

System.exit(0);

}

/** Exit the Application */

private void exitForm(java.awt.event.WindowEvent evt) {

System.exit(0);

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new WriteBoard().setVisible(true);

}

});

}

// Variables declaration - do not modify

private java.awt.Menu menu1;

private java.awt.Menu menu2;

private java.awt.MenuBar menuBar1;

private java.awt.MenuItem menuItem1;

private java.awt.MenuItem menuItem2;

private java.awt.MenuItem menuItem3;

private java.awt.MenuItem menuItem4;

private java.awt.MenuItem menuItem5;

private java.awt.MenuItem menuItem6;

private java.awt.MenuItem menuItem7;

private java.awt.MenuItem menuItem8;

private java.awt.TextArea textArea1;

// End of variables declaration

}

java记事本源代码

给你个做好了的Java的源程序的记事本,自己看看就行了的,不怎么难的···

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import javax.swing.*;

public class MyNotepad implements ActionListener{

private JFrame frame=new JFrame("新记事本");

private JTextArea jta=new JTextArea();

private String result="";

private boolean flag=true;

private File f;

private JButton jb=new JButton("开始");

private JTextField jtf=new JTextField(15);

private JTextField jt=new JTextField(15);

private JButton jbt=new JButton("替换为");

private JButton jba=new JButton("全部替换");

private Icon ic=new ImageIcon("D:\\java课堂笔记\\GUI\\11.gif");

private String value;

private int start=0;

private JFrame jf=new JFrame("查找");

private JFrame jfc=new JFrame("替换");

@Override

public void actionPerformed(ActionEvent e) {

String comm=e.getActionCommand();

if("新建".equals(comm)){

if(!(frame.getTitle().equals("新记事本"))){

if(!flag){

write();

newNew();

}else{

JFileChooser jfc=new JFileChooser("D:\\java课堂笔记");

int returnVal = jfc.showDialog(null,"保存为");

if(returnVal == JFileChooser.APPROVE_OPTION) {//选择文件后再执行下面的语句,保证了程序的健壮性

f=jfc.getSelectedFile();

flag=false;

write();

}

}

}else if(!(jta.getText().isEmpty())){

JFileChooser jfc=new JFileChooser("D:\\java课堂笔记");

int returnVal = jfc.showDialog(null,"保存为");

if(returnVal == JFileChooser.APPROVE_OPTION) {//选择文件后再执行下面的语句,保证了程序的健壮性

f=jfc.getSelectedFile();

flag=false;

write();

newNew();

}

}else{

newNew();

}

}else if("打开".equals(comm)){

JFileChooser jfc=new JFileChooser("D:\\java课堂笔记");

jfc.setDialogType(JFileChooser.OPEN_DIALOG);

int returnVal = jfc.showOpenDialog(null);

if(returnVal == JFileChooser.APPROVE_OPTION) {//选择文件后再执行下面的语句,保证了程序的健壮性

f=jfc.getSelectedFile();

frame.setTitle(f.getName());

result=read();

flag=false;

value=result;

jta.setText(result);

}

}else if("保存".equals(comm)){

JFileChooser jfc=new JFileChooser("D:\\java课堂笔记");

if(flag){

int returnVal = jfc.showDialog(null,"保存为");

if(returnVal == JFileChooser.APPROVE_OPTION) {//选择文件后再执行下面的语句,保证了程序的健壮性

f=jfc.getSelectedFile();

flag=false;

write();

}

}else{

write();

}

}else if("另存".equals(comm)){

JFileChooser jfc=new JFileChooser("D:\\java课堂笔记");

int returnVal = jfc.showDialog(null,"另存");

if(returnVal == JFileChooser.APPROVE_OPTION) {//选择文件后再执行下面的语句,保证了程序的健壮性

f=jfc.getSelectedFile();

write();

}

}else if("退出".equals(comm)){

System.exit(0);

}else if("撤销".equals(comm)){

jta.setText(value);

}else if("剪切".equals(comm)){

value=jta.getText();

jta.cut();

}else if("复制".equals(comm)){

jta.copy();

}else if("粘贴".equals(comm)){

value=jta.getText();

jta.paste();

}else if("删除".equals(comm)){

value=jta.getText();

jta.replaceSelection(null);

}else if("全选".equals(comm)){

jta.selectAll();

}else if("查找".equals(comm)){

value=jta.getText();

jf.add(jtf,BorderLayout.CENTER);

jf.add(jb,BorderLayout.SOUTH);

jf.setLocation(300,300);

jf.pack();

jf.setVisible(true);

jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

}else if("替换".equals(comm)){

value=jta.getText();

GridLayout gl=new GridLayout(3,3);

JLabel jl1=new JLabel("查找内容:");

JLabel jl2=new JLabel("替换为:");

jfc.setLayout(gl);

jfc.add(jl1);

jfc.add(jtf);

jfc.add(jb);

jfc.add(jl2);

jfc.add(jt);

jfc.add(jbt);

JLabel jl3=new JLabel();

JLabel jl4=new JLabel();

jfc.add(jl3);

jfc.add(jl4);

jfc.add(jba);

jfc.setLocation(300,300);

jfc.pack();

jfc.setVisible(true);

jfc.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

}else if("版本".equals(comm)){

JDialog jd=new JDialog(frame,"关于对话框");

jd.setSize(200,200);

JLabel l=new JLabel("哈哈哈哈哈哈哈哈哈哈呵呵呵呵呵呵呵呵呵呵呵呵呵");

jd.add(l,BorderLayout.CENTER);

jd.setLocation(100,200);

jd.setSize(300,300);

jd.setVisible(true);

// jd.pack();

jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

}else if("开始".equals(comm)||"下一个".equals(comm)){

String temp=jtf.getText();

int s=value.indexOf(temp,start);

if(value.indexOf(temp,start)!=-1){

jta.setSelectionStart(s);

jta.setSelectionEnd(s+temp.length());

jta.setSelectedTextColor(Color.GREEN);

start=s+1;

jb.setText("下一个");

// value=value.substring(s+temp.length());//不能截取字串

}else {

JOptionPane.showMessageDialog(jf, "查找完毕!", "提示", 0, ic);

jf.dispose();

}

}else if("替换为".equals(comm)){

String temp=jtf.getText();

int s=value.indexOf(temp,start);

if(value.indexOf(temp,start)!=-1){

jta.setSelectionStart(s);

jta.setSelectionEnd(s+temp.length());

jta.setSelectedTextColor(Color.GREEN);

start=s+1;

jta.replaceSelection(jt.getText());

}else {

JOptionPane.showMessageDialog(jf, "查找完毕!", "提示", 0, ic);

jf.dispose();

}

}else if("全部替换".equals(comm)){

String temp=jta.getText();

temp=temp.replaceAll(jtf.getText(), jt.getText());

jta.setText(temp);

}

}

public String read(){

String temp="";

try {

FileInputStream fis = new FileInputStream(f.getAbsolutePath());

byte[] b=new byte[1024];

while(true){

int num=fis.read(b);

if(num==-1)break;

temp=temp+new String(b,0,num);

}

fis.close();

} catch (Exception e1) {

e1.printStackTrace();

}

return temp;

}

public void write(){

try {

FileOutputStream fos=new FileOutputStream(f);

fos.write(jta.getText().getBytes());

fos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

public void newNew(){

frame.dispose();

new MyNotepad();

flag=true;

}

public MyNotepad(){

JMenuBar jmb=new JMenuBar();

String[] menuLab={"文件","编辑","帮助"};

String[][] menuItemLab={{"新建","打开","保存","另存","退出"},

{"撤销","剪切","复制","粘贴","删除","全选","查找","替换"},

{"版本"}};

for(int i=0;imenuLab.length;i++){

JMenu menu=new JMenu(menuLab[i]);

jmb.add(menu);

for(int j=0;jmenuItemLab[i].length;j++){

JMenuItem jmi=new JMenuItem(menuItemLab[i][j]);

menu.add(jmi);

jmi.addActionListener(this);

}

}

frame.setJMenuBar(jmb);

jta.setLineWrap(true);//自动换行

JScrollPane jsp=new JScrollPane(jta);//滚动窗口面板

frame.add(jsp);

jb.addActionListener(this);

jbt.addActionListener(this);

jba.addActionListener(this);

frame.setLocation(200,50);

frame.setSize(620,660);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) {

new MyNotepad();

}

}

用Java编写简易记事本源代码

importjava.awt.BorderLayout;importjava.awt.Container;importjava.awt.Font;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.InputEvent;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjavax.swing.BorderFactory;importjavax.swing.JFileChooser;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JOptionPane;importjavax.swing.JPopupMenu;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;importjavax.swing.KeyStroke;importjavax.swing.ScrollPaneConstants;importjavax.swing.SwingConstants;publicclassJNotePadUIextendsJFrame{privateJMenuItemmenuOpen;privateJMenuItemmenuSave;privateJMenuItemmenuSaveAs;privateJMenuItemmenuClose;privateJMenueditMenu;privateJMenuItemmenuCut;privateJMenuItemmenuCopy;privateJMenuItemmenuPaste;privateJMenuItemmenuAbout;privateJTextAreatextArea;privateJLabelstateBar;privateJFileChooserfileChooser;privateJPopupMenupopUpMenu;publicJNotePadUI(){super("新建文本文件");setUpUIComponent();setUpEventListener();setVisible(true);}privatevoidsetUpUIComponent(){setSize(640,480);//菜单栏JMenuBarmenuBar=newJMenuBar();//设置「文件」菜单JMenufileMenu=newJMenu("文件");menuOpen=newJMenuItem("打开");//快捷键设置menuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));menuSave=newJMenuItem("保存");menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));menuSaveAs=newJMenuItem("另存为");menuClose=newJMenuItem("关闭");menuClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));fileMenu.add(menuOpen);fileMenu.addSeparator();//分隔线fileMenu.add(menuSave);fileMenu.add(menuSaveAs);fileMenu.addSeparator();//分隔线fileMenu.add(menuClose);//设置「编辑」菜单JMenueditMenu=newJMenu("编辑");menuCut=newJMenuItem("剪切");menuCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));menuCopy=newJMenuItem("复制");menuCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));menuPaste=newJMenuItem("粘贴");menuPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));editMenu.add(menuCut);editMenu.add(menuCopy);editMenu.add(menuPaste);//设置「关于」菜单JMenuaboutMenu=newJMenu("关于");menuAbout=newJMenuItem("关于JNotePad");aboutMenu.add(menuAbout);menuBar.add(fileMenu);menuBar.add(editMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//文字编辑区域textArea=newJTextArea();textArea.setFont(newFont("宋体",Font.PLAIN,16));textArea.setLineWrap(true);JScrollPanepanel=newJScrollPane(textArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);ContainercontentPane=getContentPane();contentPane.add(panel,BorderLayout.CENTER);//状态栏stateBar=newJLabel("未修改");stateBar.setHorizontalAlignment(SwingConstants.LEFT);stateBar.setBorder(BorderFactory.createEtchedBorder());contentPane.add(stateBar,BorderLayout.SOUTH);popUpMenu=editMenu.getPopupMenu();fileChooser=newJFileChooser();}privatevoidsetUpEventListener(){//按下窗口关闭钮事件处理addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){closeFile();}});//菜单-打开menuOpen.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){openFile();}});//菜单-保存menuSave.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFile();}});//菜单-另存为menuSaveAs.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFileAs();}});//菜单-关闭文件menuClose.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){closeFile();}});//菜单-剪切menuCut.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){cut();}});//菜单-复制menuCopy.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){copy();}});//菜单-粘贴menuPaste.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){paste();}});//菜单-关于menuAbout.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){//显示对话框JOptionPane.showOptionDialog(null,"程序名称:\nJNotePad\n"+"程序设计:\n\n"+"简介:\n一个简单的文字编辑器\n"+"可作为验收Java的实现对象\n"+"欢迎网友下载研究交流\n\n"+"/","关于JNotePad",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,null,null);}});//编辑区键盘事件textArea.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEvente){processTextArea();}});//编辑区鼠标事件textArea.addMouseListener(newMouseAdapter(){publicvoidmouseReleased(MouseEvente){if(e.getButton()==MouseEvent.BUTTON3)popUpMenu.show(editMenu,e.getX(),e.getY());}publicvoidmouseClicked(MouseEvente){if(e.getButton()==MouseEvent.BUTTON1)popUpMenu.setVisible(false);}});}privatevoidopenFile(){if(isCurrentFileSaved()){//文件是否为保存状态open();//打开}else{//显示对话框intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){//确认文件保存caseJOptionPane.YES_OPTION:saveFile();//保存文件break;//放弃文件保存caseJOptionPane.NO_OPTION:open();break;}}}privatebooleanisCurrentFileSaved(){if(stateBar.getText().equals("未修改")){returnfalse;}else{returntrue;}}privatevoidopen(){//fileChooser是JFileChooser的实例//显示文件选取的对话框intoption=fileChooser.showDialog(null,null);//使用者按下确认键if(option==JFileChooser.APPROVE_OPTION){try{//开启选取的文件BufferedReaderbuf=newBufferedReader(newFileReader(fileChooser.getSelectedFile()));//设定文件标题setTitle(fileChooser.getSelectedFile().toString());//清除前一次文件textArea.setText("");//设定状态栏stateBar.setText("未修改");//取得系统相依的换行字符StringlineSeparator=System.getProperty("line.separator");//读取文件并附加至文字编辑区Stringtext;while((text=buf.readLine())!=null){textArea.append(text);textArea.append(lineSeparator);}buf.close();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"开启文件失败",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFile(){//从标题栏取得文件名称Filefile=newFile(getTitle());//若指定的文件不存在if(!file.exists()){//执行另存为saveFileAs();}else{try{//开启指定的文件BufferedWriterbuf=newBufferedWriter(newFileWriter(file));//将文字编辑区的文字写入文件buf.write(textArea.getText());buf.close();//设定状态栏为未修改stateBar.setText("未修改");}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"写入文件失败",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFileAs(){//显示文件对话框intoption=fileChooser.showSaveDialog(null);//如果确认选取文件if(option==JFileChooser.APPROVE_OPTION){//取得选择的文件Filefile=fileChooser.getSelectedFile();//在标题栏上设定文件名称setTitle(file.toString());try{//建立文件file.createNewFile();//进行文件保存saveFile();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"无法建立新文件",JOptionPane.ERROR_MESSAGE);}}}privatevoidcloseFile(){//是否已保存文件if(isCurrentFileSaved()){//释放窗口资源,而后关闭程序dispose();}else{intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){caseJOptionPane.YES_OPTION:saveFile();break;caseJOptionPane.NO_OPTION:dispose();}}}privatevoidcut(){textArea.cut();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidcopy(){textArea.copy();popUpMenu.setVisible(false);}privatevoidpaste(){textArea.paste();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidprocessTextArea(){stateBar.setText("已修改");}publicstaticvoidmain(String[]args){newJNotePadUI();}}


网站名称:java记事本课程源代码 记事本编写java程序
URL地址:http://kswsj.cn/article/hhghjo.html

其他资讯