记事本java完整代码 记事本java代码编译-成都快上网建站

记事本java完整代码 记事本java代码编译

java记事本代码

import java.awt.event.ActionListener;

专注于为中小企业提供成都网站设计、做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业贡觉免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

import java.util.EventListener;

import java.awt.event.*;

import java.awt.*;

import java.io.*;

import java.lang.*;

import java.awt.datatransfer.*;

import javax.swing.*;

public class MiniEdit extends JFrame implements ActionListener {

/**

* Method main

*

*

* @param args

*

*/

MenuBar menuBar = new MenuBar();

Menu file = new Menu("File"),

edit = new Menu("Edit"),

help = new Menu("Help");

MenuItem[] menuItem ={

new MenuItem("New"),

new MenuItem("Open"),

new MenuItem("Save"),

new MenuItem("Exit"),

new MenuItem("Select All"),

new MenuItem("Copy"),

new MenuItem("Cut"),

new MenuItem("Paste"),

new MenuItem("Help")

};

TextArea textArea = new TextArea();

String fileName = "NoName";

Toolkit toolKit = Toolkit.getDefaultToolkit();

Clipboard clipboard = toolKit.getSystemClipboard();

//opne and close message dialogs

private FileDialog openFileDialog =

new FileDialog(this,"Open File",FileDialog.LOAD);

private FileDialog saveFileDialog =

new FileDialog(this,"Save File",FileDialog.SAVE);

public static void main(String[] args) {

// TODO: Add your code here

MiniEdit MyEdit = new MiniEdit();

MyEdit.show();

}

/**

* Method MiniEdit

*

*

*/

public MiniEdit() {

// TODO: Add your code here

setTitle("MiniEdit");

setFont(new Font("Times New Roman",Font.PLAIN,15));

setBackground(Color.white);

setSize(500,500);

setMenuBar(menuBar);

menuBar.add(file);

menuBar.add(edit);

menuBar.add(help);

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

{

file.add(menuItem[i]);

edit.add(menuItem[i+4]);

}

help.add(menuItem[8]);

add(textArea);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

e.getWindow().dispose();

System.exit(0);

}

});

//add actionListener

for(int i=0;imenuItem.length;i++)

{

menuItem[i].addActionListener(this);

}

}

/**

* Method actionPerformed

*

*

* @param e

*

*/

public void actionPerformed(ActionEvent e) {

// TODO: Add your code here

Object eventSource = e.getSource();

if(eventSource == menuItem[0])//newItem

{

textArea.setText("");

}

else if(eventSource == menuItem[1])//OpenItem

{

openFileDialog.show();

fileName = openFileDialog.getDirectory()+openFileDialog.getFile();

if(fileName != null)

{

openFile(fileName);

}

}

else if(eventSource ==menuItem[2])//SaveItem

{

saveFileDialog.show();

fileName = saveFileDialog.getDirectory()+saveFileDialog.getFile();

if(fileName !=null)

{

writeFile(fileName);

}

}

else if(eventSource==menuItem[3])//exitItem

{

System.exit(0);

}

else if(eventSource == menuItem[4])//Select All

{

textArea.selectAll();

}

else if(eventSource == menuItem[5])//copy

{

String text = textArea.getSelectedText();

StringSelection selection= new StringSelection(text);

clipboard.setContents(selection,null);

}

else if(eventSource == menuItem[6])//cut

{

String text = textArea.getSelectedText();

StringSelection selection = new StringSelection(text);

clipboard.setContents(selection,null);

textArea.replaceText("",textArea.getSelectionStart(),

textArea.getSelectionEnd());

}

else if(eventSource == menuItem[7])//Paste

{

Transferable contents = clipboard.getContents(this);

if(contents==null)

return;

String text;

text="";

try{

text = (String)contents.getTransferData(DataFlavor.stringFlavor);

}catch(Exception ex){}

textArea.replaceText(text,

textArea.getSelectionStart(),textArea.getSelectionEnd());

}

else if(eventSource == menuItem[8])

{

// JOptionPane.showMessageDialog(null,"This is a MiniEdit.");

}

}

//Read file

public void openFile(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(Exception e)

{

System.out.println("Error opening file!");

}

}

//write file

public void writeFile(String fileName){

try{

File file = new File(fileName);

FileWriter write = new FileWriter(file);

write.write(textArea.getText());

write.close();

}catch(Exception e){

System.out.println("Error closing file!");

就这样交,不会错的

记事本java代码

//继承的类换一下,应该用swing包里面

class Jsben extends Frame  {   -- class Jsben extends JFrame  {

frame的方法setMenuBar(bar);和setJMenuBar(bar);这个不太一样,功能类似

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的源代码

import java.awt.BorderLayout;

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程序并运行?

1. 新建一个记事本,后缀名是  .java  ;然后在里面写一段java的代码,如图:

2.把写好的java文件丢进D盘,就是第一步给出的那个class文件;

3. 打开dos界面 开始-〉运行-〉cmd-〉 这个是命令行模式,选择D盘,如图:

4.选择D盘之后,在命令提示符中输入“javac 文件名.java”,我的文件名为java,所以输入javac java.java然后回车,等待编译。这时候你就会发现它提示说javac不是内部文件。接下来就是java环境变量设置的问题了;

5.下载一个jdk执行默认安装。例如我下的jdk版本是: jdk-6u10-rc2-bin-b32-windows-i586-p-12_sep_2008.exe;

6.配置环境:右击我的电脑点属性,进去点高级就能看到环境变量。点进去就能设置你的系统变量了,如图:

6-1。变量名:classpath    变量值:(.;C:\Program Files\Java\jdk1.6.0_10\lib;)括号里面都是 (主要我们在编译运行程序的时候通过classpath可以帮助我们找到一些需要的系统类,“.”号是表示当前路径;“;”号是用来隔开多个变量值,如果你的系统里面已经有classpath环 境变量,就不用新建了,直接加“;”号,在后面加新值);如图所示

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完整代码 记事本java代码编译
网站路径:http://kswjz.com/article/hiehoo.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流