java记事本源码
‘壹’ 求助java记事本的原代码(和WINDOWS一样的)
//package net.src.net;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.color.*;
import java.awt.font.*;
import javax.swing.undo.*;
public class Note extends JFrame
{
boolean isChange=false;
boolean wasChange=false;
JMenuBar menuBar=new JMenuBar();
JMenu menuFile=new JMenu("File");
JMenuItem menuFileOpen=new JMenuItem("Open..");
JMenuItem menuFileSave=new JMenuItem("Save..");
JMenuItem menuFileExit=new JMenuItem("Exit");
JMenu menuEdit=new JMenu("Edit");
JMenuItem menuFileCut=new JMenuItem("Cut");
JMenuItem font=new JMenuItem("Font");
JMenuItem menuFilePaste=new JMenuItem("Paste");
JTextArea fileArea=new JTextArea();
public Note()
{
this.setTitle("记事本");
Toolkit tool=this.getToolkit();//窗口图标!
Image myimage=tool.getImage("戒指.jpg");
this.setIconImage(myimage);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exit();
}
});
menuFileOpen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fileOpen_actionPerformed(e);
}
});
menuFileSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fileSave_actionPerformed(e);
}
});
menuFileExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fileExit_actionPerformed(e);
}
});
menuFileCut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fileCut_actionPerformed(e);
}
});
menuFilePaste.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
filePaste_actionPerformed(e);
}
});
font.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
fileColor_actionPerformed(e);
}
});
fileArea.getDocument().addDocumentListener(new DocumentListener()
{
public void insertUpdate(DocumentEvent e)
{
wasChange=isChange;
isChange=true;
}
public void removeUpdate(DocumentEvent e)
{
wasChange=isChange;
isChange=true;
}
public void changedUpdate(DocumentEvent e)
{
wasChange=isChange;
isChange=true;
}
});
setSize(500,450);
menuBar.add(menuFile);
menuFile.setMnemonic('F');
menuBar.add(menuEdit);
menuEdit.setMnemonic('E');
menuFile.add(menuFileOpen);
menuFileOpen.setMnemonic('O');//访问健;
menuFileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));//快捷健;
menuFile.add(menuFileSave);
menuFileSave.setMnemonic('S');
menuFileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
menuFile.addSeparator();
menuFile.add(menuFileExit);
menuFileExit.setMnemonic('E');
menuEdit.add(menuFileCut);
menuFileCut.setMnemonic('C');
menuFileCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));
menuEdit.add(menuFilePaste);
menuFilePaste.setMnemonic('P');
menuFilePaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_MASK));
menuEdit.add(font);
font.setMnemonic('N');
font.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
this.getContentPane().add(new JScrollPane(fileArea));
setJMenuBar(menuBar);
fileArea.setLineWrap(true);
}
public void fileExit_actionPerformed(ActionEvent e)
{
System.exit(0);
}
public void fileOpen_actionPerformed(ActionEvent e)
{
//以下是filter;
JFileChooser fileChooser=new JFileChooser();
//fileChooser.addChoosableFileFilter(new myFilter("*.txt","Files(*.txt)"));
fileChooser.addChoosableFileFilter(fileChooser.getFileFilter());
if(fileChooser.APPROVE_OPTION!=fileChooser.showOpenDialog(this))return;
//以下是文件读
BufferedReader dataIn=null;
try
{
dataIn=new BufferedReader(new FileReader(fileChooser.getSelectedFile().getPath()));
String c=null;
do
{
c=dataIn.readLine();
if(c!=null)
fileArea.append(c+"\n");
}
while(c!=null);
}
catch(Exception ex)
{
System.out.println("Catch exception:"+ex.toString());
}
}
public void exit()
{
if(isChange==false)
System.exit(1);
else
{
int decision=JOptionPane.showConfirmDialog(this,"The File has Change.\n"+"Do you want to save the change?",
"Notepad",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
if (decision == JOptionPane.YES_OPTION)
{
//以下是将文件写入计算机!
try {
JFileChooser fileSave = new JFileChooser();
fileSave.setDialogTitle("保存文件");
//fileSave.addChoosableFileFilter(new myFilter("*.txt","Files(*.txt)"));
fileSave.addChoosableFileFilter(fileSave.getFileFilter());
if (fileSave.APPROVE_OPTION != fileSave.showSaveDialog(this))
return;
BufferedWriter dataOut = new BufferedWriter(new BufferedWriter(new
FileWriter(fileSave.getSelectedFile())));
String c = null;
do {
String str = fileArea.getText();
dataOut.write(str);
dataOut.close();
}
while (c != null);
}
catch (Exception e2) {
System.out.println("Catch exception:有错误!" + e2.toString());
}
}
else if (decision == JOptionPane.NO_OPTION)
System.exit(1);
else if (decision == JOptionPane.CANCEL_OPTION);
;
}
//innerclass.fileSave_actionPerformed();
}
public void fileSave_actionPerformed(ActionEvent e1)
{
//以下是将文件写入计算机!
try
{
JFileChooser fileSave=new JFileChooser();
fileSave.setDialogTitle("保存文件" );
//fileSave.addChoosableFileFilter(new myFilter("*.txt","Files(*.txt)"));
fileSave.addChoosableFileFilter(fileSave.getFileFilter());
if(fileSave.APPROVE_OPTION!=fileSave.showSaveDialog(this))return;
BufferedWriter dataOut=new BufferedWriter(new BufferedWriter(new FileWriter(fileSave.getSelectedFile()+".txt")));
//RandomAccessFile dataOut=new RandomAccessFile(fileSave.getSelectedFile(),"rw");
String c=null;
do
{
String str=fileArea.getText();
dataOut.write(str);
dataOut.close();
}
while(c!=null);
}
catch(Exception e2)
{
System.out.println("Catch exception:有错误!"+e2.toString());
}
}
public static void main(String arg[])
{
Note nt=new Note();
nt.show();
}
public void fileCut_actionPerformed(ActionEvent e)
{
fileArea.cut();
}
public void filePaste_actionPerformed(ActionEvent e)
{
fileArea.paste();
}
public void fileColor_actionPerformed(ActionEvent e)
{
JColorChooser fileColor=new JColorChooser();
//fileArea.setForeground(fileColor.showDialog(this,"颜色",Color.red));
//fileArea.setSelectionColor(fileColor.showDialog(this,"颜色",Color.red));
fileArea.setSelectionColor(fileColor.showDialog(this,"颜色",Color.black));
}
}
//文件过滤类怎么写!
‘贰’ 用java实现有简单登录窗口的简单记事本(要源代码)
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class DengLu extends JFrame {
public JLabel name = new JLabel("用户名");
public JLabel pass = new JLabel("口令");
public JTextField userName = new JTextField();
public JPasswordField passWord = new JPasswordField();
public Button bok = new Button("登陆");
public Button bexit = new Button("退出");
//别人的作业,登录、密码
public DengLu() {
this.setContentPane(new MyPanel());
setTitle("登录(快快乐乐)聊天室");
setLayout(null);
setSize(500, 400);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frm = this.getSize();
setLocation( (scr.width - frm.width) / 2,
(scr.height - frm.height) / 2 - 18);
name.setBounds(70, 260, 120, 20);
userName.setBounds(120, 260, 120, 27);
pass.setBounds(70, 300, 120, 20);
passWord.setBounds(120, 300, 120, 27);
passWord.setEchoChar('*');
bok.setBounds(340, 260, 100, 28);
bexit.setBounds(340, 300, 100, 28);
add(name);
add(userName);
add(pass);
add(passWord);
add(bok);
add(bexit);
setVisible(true);
bexit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
bok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (userName.getText().equals("")) {
JOptionPane.showMessageDialog(null, "用户名不能为空!");
}
else if (passWord.getText().equals("")) {
JOptionPane.showMessageDialog(null, "密码不能为空!");
}
else {
if (userName.getText().equals("admin") && passWord.getText().equals("admin")) {
dispose();
new MyFrame();
}
else {
JOptionPane.showMessageDialog(null, "密码错误");
userName.setText(null);
passWord.setText(null);
}
}
}
});
}
public static void main(String args[]) {
new DengLu(); }
private class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
super.paintComponent(g);
Image img = Toolkit.getDefaultToolkit().getImage("zsjm.jpg");
g2.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
}
}
这是别人的,能用。
‘叁’ 求一个用JAVA写的简单的记事本源代码程序
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.datatransfer.*;
class MyMenuBar extends MenuBar{
public MyMenuBar(Frame parent){
parent.setMenuBar(this);
}
public void addMenus(String [] menus){
for(int i=0;i<menus.length;i++)
add(new Menu(menus[i]));
}
public void addMenuItems(int menuNumber,String[] items){
for(int i=0;i<items.length;i++){
if(items[i]!=null)
getMenu(menuNumber).add(new MenuItem(items[i]));
else getMenu(menuNumber).addSeparator();
}
}
public void addActionListener(ActionListener al){
for(int i=0;i<getMenuCount();i++)
for(int j=0;j<getMenu(i).getItemCount();j++)
getMenu(i).getItem(j).addActionListener(al);
}
}
class MyFile{
private FileDialog fDlg;
public MyFile(Frame parent){
fDlg=new FileDialog(parent,"",FileDialog.LOAD);
}
private String getPath(){
return fDlg.getDirectory()+"\\"+fDlg.getFile();
}
public String getData() throws IOException{
fDlg.setTitle("打开");
fDlg.setMode(FileDialog.LOAD);
fDlg.setVisible(true);
BufferedReader br=new BufferedReader(new FileReader(getPath()));
StringBuffer sb=new StringBuffer();
String aline;
while((aline=br.readLine())!=null)
sb.append(aline+'\n');
br.close();
return sb.toString();
}
public void setData(String data) throws IOException{
fDlg.setTitle("保存");
fDlg.setMode(FileDialog.SAVE);
fDlg.setVisible(true);
BufferedWriter bw=new BufferedWriter(new FileWriter(getPath()));
bw.write(data);
bw.close();
}
}
class MyClipboard{
private Clipboard cb;
public MyClipboard(){
cb=Toolkit.getDefaultToolkit().getSystemClipboard();
}
public void setData(String data){
cb.setContents(new StringSelection(data),null);
}
public String getData(){
Transferable content=cb.getContents(null);
try{
return (String) content.getTransferData(DataFlavor.stringFlavor);
//DataFlavor.stringFlavor会将剪贴板中的字符串转换成Unicode码形式的String对象。
//DataFlavor类是与存储在剪贴板上的数据的形式有关的类。
}catch(Exception ue){}
return null;
}
}
class MyFindDialog extends Dialog implements ActionListener{
private Label lFind=new Label("查找字符串");
private Label lReplace=new Label("替换字符串");
private TextField tFind=new TextField(10);
private TextField tReplace=new TextField(10);
private Button bFind=new Button("查找");
private Button bReplace=new Button("替换");
private TextArea ta;
public MyFindDialog(Frame owner,TextArea ta){
super(owner,"查找",false);
this.ta=ta;
setLayout(null);
lFind.setBounds(10,30,80,20);
lReplace.setBounds(10,70,80,20);
tFind.setBounds(90,30,90,20);
tReplace.setBounds(90,70,90,20);
bFind.setBounds(190,30,80,20);
bReplace.setBounds(190,70,80,20);
add(lFind);
add(tFind);
add(bFind);
add(lReplace);
add(tReplace);
add(bReplace);
setResizable(false);
bFind.addActionListener(this);
bReplace.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MyFindDialog.this.dispose();
}
});
}//构造函数结束
public void showFind(){
setTitle("查找");
setSize(280,60);
setVisible(true);
}
public void showReplace(){
setTitle("查找替换");
setSize(280,110);
setVisible(true);
}
private void find(){
String text=ta.getText();
String str=tFind.getText();
int end=text.length();
int len=str.length();
int start=ta.getSelectionEnd();
if(start==end) start=0;
for(;start<=end-len;start++){
if(text.substring(start,start+len).equals(str)){
ta.setSelectionStart(start);
ta.setSelectionEnd(start+len);
return;
}
}
//若找不到待查字符串,则将光标置于末尾
ta.setSelectionStart(end);
ta.setSelectionEnd(end);
}
public Button getBFind() {
return bFind;
}
private void replace(){
String str=tReplace.getText();
if(ta.getSelectedText().equals(tFind.getText()))
ta.replaceRange(str,ta.getSelectionStart(),ta.getSelectionEnd());
else find();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bFind)
find();
else if(e.getSource()==bReplace)
replace();
}
}
public class MyMemo extends Frame implements ActionListener{
private TextArea editor=new TextArea(); //可编辑的TextArea
private MyFile mf=new MyFile(this);//MyFile对象
private MyClipboard cb=new MyClipboard();
private MyFindDialog findDlg=new MyFindDialog(this,editor);
public MyMemo(String title){ //构造函数
super(title);
MyMenuBar mb=new MyMenuBar(this);
//添加需要的菜单及菜单项
mb.addMenus(new String[]{"文件","编辑","查找","帮助"});
mb.addMenuItems(0,new String[]{"新建","打开","保存",null,"全选"});
mb.addMenuItems(1,new String[]{"剪贴","复制","粘贴","清除",null,"全选"});
mb.addMenuItems(2,new String[]{"查找",null,"查找替换"});
mb.addMenuItems(3,new String[]{"我的记事本信息"});
add(editor); //为菜单项注册动作时间监听器
mb.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MyMemo.this.dispose();
}
}); //分号不能忘了
} //构造函数完
public void actionPerformed(ActionEvent e){
String selected=e.getActionCommand(); //获取菜单项标题
if(selected.equals("新建"))
editor.setText("");
else if(selected.equals("打开")){
try{
editor.setText(mf.getData());
}catch(IOException ie){}
}
else if(selected.equals("保存")){
try{
mf.setData(editor.getText());
}catch(IOException ie){}
}
else if(selected.equals("退出")){
dispose();
}
else if(selected.equals("剪贴")){
//将选中的字符串复制到剪贴板中并清除字符串
cb.setData(editor.getSelectedText());
editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());
}
else if(selected.equals("复制")){
cb.setData(editor.getSelectedText());
}
else if(selected.equals("粘贴")){
String str=cb.getData();
editor.replaceRange(str,editor.getSelectionStart(),editor.getSelectionEnd());
//粘贴在光标位置
}
else if(selected.equals("清除")){
editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());
}
else if(selected.equals("全选")){
editor.setSelectionStart(0);
editor.setSelectionEnd(editor.getText().length());
}
else if(selected.equals("查找")){
findDlg.showFind();
}
else if(selected.equals("查找替换")){
findDlg.showReplace();
}
}
public static void main(String[] args){
MyMemo memo=new MyMemo("记事本");
memo.setSize(650,450);
memo.setVisible(true);
}
}
‘肆’ 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.();
}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;i<menuLab.length;i++){
JMenu menu=new JMenu(menuLab[i]);
jmb.add(menu);
for(int j=0;j<menuItemLab[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;{privateJMenuItemmenuOpen;privateJMenuItemmenuSave;privateJMenuItemmenuSaveAs;privateJMenuItemmenuClose;privateJMenueditMenu;privateJMenuItemmenuCut;privateJMenuItemmenuCopy;privateJMenuItemmenuPaste;privateJMenuItemmenuAbout;privateJTextAreatextArea;privateJLabelstateBar;;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){();}});//菜单-粘贴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;}}}(){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);}privatevoid(){textArea.();popUpMenu.setVisible(false);}privatevoidpaste(){textArea.paste();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidprocessTextArea(){stateBar.setText("已修改");}publicstaticvoidmain(String[]args){newJNotePadUI();}}
‘陆’ 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;i<4;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;i<menuItem.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])//
{
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程序代码
天啊,冖_Na0为什么会有我编的记事本代码呢???呵呵……你肯定是“请教”过我的吧??
呵呵……我自己编了一个,不过呢,没有windows那么多的功能啊。
涉及到两个文件:
第一个文件中的代码:
packageMyProject;
importjava.awt.BorderLayout;
importjavax.swing.JPanel;
importjavax.swing.JFrame;
importjava.awt.Dimension;
importjavax.swing.JMenuBar;
importjavax.swing.JMenu;
importjavax.swing.JMenuItem;
importjavax.swing.JLabel;
importjava.awt.Rectangle;
importjavax.swing.JTextArea;
importjavax.swing.JScrollPane;
importjava.awt.datatransfer.*;
importjava.io.*;
{
=1L;
privateJPaneljContentPane=null;
privateJMenuBarjJMenuBar=null;
privateJMenujMenu=null;
privateJMenujMenu1=null;
privateJMenujMenu2=null;
privateJMenuItemjMenuItem=null;
privateJMenuItemjMenuItem1=null;
privateJMenuItemjMenuItem2=null;
privateJMenuItemjMenuItem3=null;
privateJLabeljLabel=null;
privateJScrollPanejScrollPane=null;
privateJTextAreajTextArea=null;
privateJMenuItemjMenuItem4=null;
privateJMenuItemjMenuItem5=null;
privateJMenuItemjMenuItem6=null;
privateJMenuItemjMenuItem7=null;
=null;
privatestaticStringtextstr="";///用于记录文本文件的路径
privateFilemyFile=null;
privateFileReadermyrder=null;
privateFileWritermywr=null;
/**
*Thisisthedefaultconstructor
*/
publicMainFrame(){
super();
initialize();
}
/**
*Thismethodinitializesthis
*
*@returnvoid
*/
privatevoidinitialize(){
this.setSize(412,350);
this.setJMenuBar(getJJMenuBar());
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
this.addWindowListener(newjava.awt.event.WindowAdapter(){
publicvoidwindowActivated(java.awt.event.WindowEvente){
if(!textstr.equals("")){
try{
myFile=newFile(textstr);
if(!myFile.exists()){
myFile.createNewFile();
}
myrder=newFileReader(myFile);
char[]mychar=newchar[(int)myFile.length()];
myrder.read(mychar);
Stringtmp=newString(mychar);
jTextArea.setText(tmp);
myrder.close();
}
catch(Exceptionee){
ee.printStackTrace();
}
}
}
publicvoidwindowClosing(java.awt.event.WindowEvente){
System.exit(0);
}
});
this.setVisible(true);
myMainFrame=this;
}
/**
*
*
*@returnjavax.swing.JPanel
*/
privateJPanelgetJContentPane(){
if(jContentPane==null){
jLabel=newJLabel();
jLabel.setBounds(newRectangle(15,18,65,18));
jLabel.setText("文件内容:");
jContentPane=newJPanel();
jContentPane.setLayout(null);
jContentPane.add(jLabel,null);
jContentPane.add(getJScrollPane(),null);
}
returnjContentPane;
}
/**
*
*
*@returnjavax.swing.JMenuBar
*/
privateJMenuBargetJJMenuBar(){
if(jJMenuBar==null){
jJMenuBar=newJMenuBar();
jJMenuBar.add(getJMenu());
jJMenuBar.add(getJMenu1());
jJMenuBar.add(getJMenu2());
}
returnjJMenuBar;
}
/**
*ThismethodinitializesjMenu
*
*@returnjavax.swing.JMenu
*/
privateJMenugetJMenu(){
if(jMenu==null){
jMenu=newJMenu();
jMenu.setText("文件");
jMenu.add(getJMenuItem());
jMenu.add(getJMenuItem1());
jMenu.add(getJMenuItem2());
jMenu.add(getJMenuItem3());
}
returnjMenu;
}
/**
*ThismethodinitializesjMenu1
*
*@returnjavax.swing.JMenu
*/
privateJMenugetJMenu1(){
if(jMenu1==null){
jMenu1=newJMenu();
jMenu1.setText("编辑");
jMenu1.add(getJMenuItem4());
jMenu1.add(getJMenuItem5());
jMenu1.add(getJMenuItem6());
}
returnjMenu1;
}
/**
*ThismethodinitializesjMenu2
*
*@returnjavax.swing.JMenu
*/
privateJMenugetJMenu2(){
if(jMenu2==null){
jMenu2=newJMenu();
jMenu2.setText("帮助");
jMenu2.add(getJMenuItem7());
}
returnjMenu2;
}
/**
*
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem(){
if(jMenuItem==null){
jMenuItem=newJMenuItem();
jMenuItem.setText("打开");
jMenuItem.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
MainFrame.this.myMainFrame.setEnabled(false);
SelectTextFilemysl=newSelectTextFile();
mysl.setVisible(true);
}
});
}
returnjMenuItem;
}
/**
*1
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem1(){
if(jMenuItem1==null){
jMenuItem1=newJMenuItem();
jMenuItem1.setText("关闭");
jMenuItem1.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
try{
myFile=null;
}
catch(Exceptionee){
ee.printStackTrace();
}
jTextArea.setText("");
}
});
}
returnjMenuItem1;
}
/**
*2
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem2(){
if(jMenuItem2==null){
jMenuItem2=newJMenuItem();
jMenuItem2.setText("保存");
jMenuItem2.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
try{
Stringtmp=jTextArea.getText();
char[]mychar=tmp.toCharArray();
myFile.delete();
myFile.createNewFile();
mywr=newFileWriter(myFile);
mywr.write(mychar);
mywr.close();
}
catch(Exceptionee){
ee.printStackTrace();
}
}
});
}
returnjMenuItem2;
}
/**
*3
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem3(){
if(jMenuItem3==null){
jMenuItem3=newJMenuItem();
jMenuItem3.setText("退出");
jMenuItem3.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
System.exit(0);
}
});
}
returnjMenuItem3;
}
/**
*
*
*@returnjavax.swing.JScrollPane
*/
(){
if(jScrollPane==null){
jScrollPane=newJScrollPane();
jScrollPane.setBounds(newRectangle(15,46,371,225));
jScrollPane.setViewportView(getJTextArea());
}
returnjScrollPane;
}
/**
*
*
*@returnjavax.swing.JTextArea
*/
privateJTextAreagetJTextArea(){
if(jTextArea==null){
jTextArea=newJTextArea();
}
returnjTextArea;
}
/**
*4
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem4(){
if(jMenuItem4==null){
jMenuItem4=newJMenuItem();
jMenuItem4.setText("复制");
jMenuItem4.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
MainFrame.this.setClipboardText(MainFrame.this.getToolkit().getSystemClipboard(),jTextArea.getSelectedText());
}
});
}
returnjMenuItem4;
}
/**
*5
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem5(){
if(jMenuItem5==null){
jMenuItem5=newJMenuItem();
jMenuItem5.setText("剪切");
jMenuItem5.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
MainFrame.this.setClipboardText(MainFrame.this.getToolkit().getSystemClipboard(),jTextArea.getSelectedText());
jTextArea.setText(jTextArea.getText().substring(0,jTextArea.getSelectionStart()));
}
});
}
returnjMenuItem5;
}
/**
*6
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem6(){
if(jMenuItem6==null){
jMenuItem6=newJMenuItem();
jMenuItem6.setText("黏贴");
jMenuItem6.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
try{
jTextArea.setText(jTextArea.getText().substring(0,jTextArea.getSelectionStart()));
jTextArea.setText(jTextArea.getText()+(MainFrame.this.getClipboardText(MainFrame.this.getToolkit().getSystemClipboard())));
}
catch(Exceptionee){
ee.printStackTrace();
}
}
});
}
returnjMenuItem6;
}
/**
*7
*
*@returnjavax.swing.JMenuItem
*/
privateJMenuItemgetJMenuItem7(){
if(jMenuItem7==null){
jMenuItem7=newJMenuItem();
jMenuItem7.setText("关于记事本");
jMenuItem7.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEvente){
////暂无代码!!
}
});
}
returnjMenuItem7;
}
publicstaticvoidmain(Stringargs[]){
newMainFrame();
}
(){
returnmyMainFrame;
}
(MainFramemyMainFrame){
MainFrame.myMainFrame=myMainFrame;
}
publicstaticStringgetTextstr(){
returntextstr;
}
publicstaticvoidsetTextstr(Stringtextstr){
MainFrame.textstr=textstr;
}
(Clipboardclip)throwsException{
TransferableclipT=clip.getContents(null);//获取剪切板中的内容
if(clipT!=null){
if(clipT.isDataFlavorSupported(DataFlavor.stringFlavor))//检查内容是否是文本类型
return(String)clipT.getTransferData(DataFlavor.stringFlavor);
}
returnnull;
}
(Clipboardclip,StringwriteMe){
TransferabletText=newStringSelection(writeMe);
clip.setContents(tText,null);
}
}//@jve:decl-index=0:visual-constraint="10,10"
第二个文件中的代码:
(太长了,贴不上来)
整个效果就是实现了基本的打开、关闭、保存、退出的功能。
效果如图:
‘捌’ 记事本java源码怎么生成可执行文件
如果你只是用单个java文件测试的话,可以先创建Test.java类,然后执行javac Test.java编译成class文件,class文件就可以执行 java Test
你如果是要将这个执行命令保存成一个文档。直接新建一个文本 输入java Test然后保存成xx.bat格式就可以在windows上面点击执行了。注意这个文件必须与你class文件路径一致。
如果你是一个包含了更多功能的项目,可以使用eclipse打包成可执行jar包,注意指定main方法入口,然后使用java命令执行jar包。如果是要将jar包变成exe执行文件,可以使用转换工具。比如exe4j.
前提是你的jdk环境都安装好了。
‘玖’ java:求一个记事本源代码。要可以直接运行的。
//文件功能;
if(e.getSource()==fileNew)//新建
{
area.setText("");
}
if(e.getSource()==fileOpen)//打开
{
chooser=new JFileChooser();
int result=chooser.showOpenDialog(this);
String path=chooser.getSelectedFile().getPath();
System.out.println(path);
String s="";
if(result==chooser.APPROVE_OPTION)
{
int n=0;
try
{
r=new FileReader(path);
while((n=r.read())!=-1)
{
s+=(char)n;
}
area.setText(s);
r.close();
}catch(IOException ex)
{
ex.printStackTrace();
}
}
}
if(e.getSource()==fileSaveAs)//另存为
{
chooser.setDialogTitle("另存为");
chooser=new JFileChooser();
int result=chooser.showSaveDialog(this);
String s=chooser.getSelectedFile().getPath();
String surs=chooser.getName();
if(result==JFileChooser.APPROVE_OPTION)
{
if(s.endsWith(surs)==false)
{
try
{
w=new FileWriter(s,false);
w.write(area.getText());
w.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
else
{
int n=JOptionPane.showConfirmDialog(this,s+"已存在。要替换它吗?","记事本",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
try
{
w=new FileWriter(s,false);
w.write(area.getText());
w.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
}
if(e.getSource()==fileExit)//退出
{
MassageDialog massagedialog=new MassageDialog(this);
massagedialog.setVisible(true);
}
//编辑功能;
if(e.getSource()==editUndo)//撤销
{
try
{
undoManager.undoOrRedo();
} catch (CannotRedoException cre)
{
cre.printStackTrace();
}
updateButtons();
}
if(e.getSource()==editCut)//剪切
area.cut();
if(e.getSource()==editCopy)//复制
area.();
if(e.getSource()==editPaste)//粘贴
area.paste();
if(e.getSource()==editFind)//查找
{
FindDialog findDialog=new FindDialog(this,area);
findDialog.setVisible(true);
}
if(e.getSource()==editReplace)
{
ReplaceDialog replaceDialog=new ReplaceDialog(this,area);
replaceDialog.setVisible(true);
}
if(e.getSource()==editDelete)//删除
area.replaceSelection("");
//area.replaceRange("",area.getSelectionStart(),area.getSelectionEnd());
if(e.getSource()==editSeletedAll)//全选
area.selectAll();
if(e.getSource()==editTime)//时间
{
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("hh:mm yyyy-MM-dd");
area.append(df.format(date));
}
//格式;
if(e.getSource()==formatFont)//字体
{
FontDialog fontdialog=new FontDialog(this,area);
fontdialog.setVisible(true);
}
if(e.getSource()==formatAutoline)//自动换行
{
if(formatAutoline.getState()==true)
{
area.setLineWrap(true);
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
if(formatAutoline.getState()==false)
{
area.setLineWrap(false);
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
}
}
public static void main(String[] args)
{
new Notepad();
}
}
//点击文件的“退出”按钮时,弹出的提示对话框;
class MassageDialog extends JDialog implements ActionListener
{
JButton quit,canel;
JPanel p;
JLabel hints;//提示信息;
public MassageDialog(JFrame f)
{
this.setBounds(100,100,250,100);
this.setTitle("提示");
this.setModal(true);
this.getContentPane().setLayout(new FlowLayout());
quit=new JButton("退出");
canel=new JButton("取消");
p=new JPanel();
quit.addActionListener(this);
canel.addActionListener(this);
hints=new JLabel("你确定要放弃所编辑的内容,退出吗?");
p.add(quit);
p.add(canel);
this.getContentPane().add(hints);
this.getContentPane().add(p);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit)//退出
System.exit(0);
if(e.getSource()==canel)//取消
this.setVisible(false);
}
}
//字体对话框
class FontDialog extends JDialog implements ActionListener,ListSelectionListener
{
JTextArea area;
JLabel fontFamily,fontStyle,fontSize,labelModel;
JTextField textFontFamily,textFontStyle,textFontSize;
JList listFont,listFontStyle,listFontSize;;
JButton enter,canel;
JPanel ptop,pbottom,ptwo,pone;
JScrollPane spLeft,spRight;
String fonts[]={"黑体","仿宋GB2321","华文行楷","楷体_GB2312","宋体","宋体-PUA","新宋体","Arial Black","Arial","MS PGothic","Lucida Sans"};
String styles[]={"常规","斜体","粗体","粗斜体"};
String sizes[]=new String[40];
String font;
int style,size;
public FontDialog(JFrame f,JTextArea area)
{
this.area=area;
this.setTitle("字体");
this.setModal(true);
this.setBounds(200,200,400,350);
this.getContentPane().setLayout(new FlowLayout());
ptop=new JPanel(new GridLayout(2,3));
fontFamily=new JLabel("字体(F):");
fontStyle=new JLabel("字形(Y):");
fontSize=new JLabel("大小(S):");
ptop.add(fontFamily);
ptop.add(fontStyle);
ptop.add(fontSize);
textFontFamily=new JTextField(10);
textFontStyle=new JTextField(10);
textFontSize=new JTextField(10);
ptop.add(textFontFamily);
ptop.add(textFontStyle);
ptop.add(textFontSize);
pbottom=new JPanel(new GridLayout(1,3));
listFont=new JList(fonts);
listFont.setSelectedValue("宋体",true);
listFont.addListSelectionListener(this);
textFontFamily.setText((String) listFont.getSelectedValue());
listFontStyle=new JList(styles);
listFontStyle.setSelectedValue("常规",true);
textFontStyle.setText((String) listFontStyle.getSelectedValue());
listFontStyle.addListSelectionListener(this);
for(int i=0;i<sizes.length;i++)
{
sizes[i]=String.valueOf(i+8);
}
listFontSize=new JList(sizes);
listFontSize.setSelectedValue("12",true);
textFontSize.setText((String) listFontSize.getSelectedValue());
listFontSize.addListSelectionListener(this);
spLeft=new JScrollPane(listFont,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
spRight=new JScrollPane(listFontSize,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
pbottom.add(spLeft);
pbottom.add(listFontStyle);
pbottom.add(spRight);
ptwo=new JPanel(new GridLayout(2,1));
enter=new JButton("确定");
canel=new JButton("取消");
enter.addActionListener(this);
canel.addActionListener(this);
ptwo.add(enter);
ptwo.add(canel);
pone=new JPanel();
pone.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray,2),"示例",TitledBorder.LEFT,TitledBorder.CENTER,new Font("宋体",0,13),Color.blue));
labelModel=new JLabel(" 微软中文软件 ");
labelModel.setBorder(BorderFactory.createLoweredBevelBorder());
pone.add(labelModel);
this.getContentPane().add(ptop);
this.getContentPane().add(pbottom);
this.getContentPane().add(ptwo);
this.getContentPane().add(pone);
}
public void valueChanged(ListSelectionEvent e) //字体
{
if(e.getSource()==listFont)
{
textFontFamily.setText((String) listFont.getSelectedValue());
font=textFontFamily.getText();
style=listFontStyle.getSelectedIndex();
size=Integer.parseInt((String) listFontSize.getSelectedValue());
labelModel.setFont(new Font(font,style,size));
}
if(e.getSource()==listFontStyle)//字形
{
textFontStyle.setText((String)listFontStyle.getSelectedValue());
int n=listFontStyle.getSelectedIndex();
switch(n)
{
case 0:
style=Font.PLAIN;
break;
case 1:
style=Font.ITALIC;
break;
case 2:
style=Font.BOLD;
break;
default:
style=Font.BOLD+Font.ITALIC;
break;
}
labelModel.setFont(new Font(font,style,size));
}
if(e.getSource()==listFontSize)//字体大小
{
textFontSize.setText((String)listFontSize.getSelectedValue());
size=Integer.parseInt(textFontSize.getText());
labelModel.setFont(new Font(font,style,size));
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==enter)
{
if(area.getText()=="")
this.repaint(1000);
else
{
area.setFont(new Font(font,style,size));
this.setVisible(false);
}
}
if(e.getSource()==canel)
{
this.dispose();
}
}
}
//查找对话框
class FindDialog extends JDialog implements ActionListener,CaretListener
{
JTextArea area;
JTextField jtContent;
JButton jbFindNext,jbcanel;
JLabel jlFindContent;
int index=0;
int location;
public FindDialog(JFrame j,JTextArea area)
{
this.area=area;
this.setTitle("查找");
this.setBounds(150,150,300,120);
this.getContentPane().setLayout(new FlowLayout());
jlFindContent=new JLabel("查找内容(N):");
jtContent=new JTextField(17);
jtContent.addCaretListener(this);
jbFindNext=new JButton("查找下一个(F)");
jbFindNext.setEnabled(false);
jbFindNext.addActionListener(this);
jbcanel=new JButton("取消");
jbcanel.addActionListener(this);
this.getContentPane().add(jlFindContent);
this.getContentPane().add(jtContent);
this.getContentPane().add(jbFindNext);
this.getContentPane().add(jbcanel);
}
public void actionPerformed(ActionEvent e)
{
String superText=jtContent.getText();
if(e.getSource()==jbFindNext)//查找下一个
{
location=area.getText().indexOf(superText,index);//从头开始查找,返回第一个字串所在的索引location
if(location!=-1)
{
area.setSelectionStart(location);
area.setSelectionEnd(location+superText.length());
index=location+superText.length()+1;
}
if(location==-1)
JOptionPane.showMessageDialog(this,"没有找到\""+superText+"\"");
}
if(e.getSource()==jbcanel)//取消
this.setVisible(false);
}
public void caretUpdate(CaretEvent e)
{
if(jtContent.getText()!="")
{
jbFindNext.setEnabled(true);
}
else
jbFindNext.setEnabled(false);
}
}
//替换对话框
class ReplaceDialog extends JDialog implements ActionListener
{
JLabel jlFindContent,jlReplaceContent;
JTextField jtFindContent,jtReplaceContent;
JButton jbFindNext,jbReplace,jbReplaceAll,jbCanel;
JPanel contentPane,buttonPane;
JTextArea area;
int index=0;
int location;
public ReplaceDialog(JFrame j,JTextArea area)
{
this.setTitle("替换");
this.setModal(true);
this.area=area;
this.setBounds(150,150,480,200);
this.getContentPane().setLayout(new FlowLayout());
contentPane=new JPanel();
buttonPane=new JPanel(new GridLayout(4,1));
jlFindContent=new JLabel("查找内容:");
jlReplaceContent=new JLabel("替换为:");
jtFindContent=new JTextField(15);
jtReplaceContent=new JTextField(15);
jbFindNext=new JButton("查找下一个(F)");
jbReplace=new JButton("替换(R)");
jbReplaceAll=new JButton("全部替换(A)");
jbCanel=new JButton("取消");
jbFindNext.addActionListener(this);
jbReplace.addActionListener(this);
jbReplaceAll.addActionListener(this);
jbCanel.addActionListener(this);
contentPane.add(jlFindContent);
contentPane.add(jtFindContent);
contentPane.add(jlReplaceContent);
contentPane.add(jtReplaceContent);
buttonPane.add(jbFindNext);
buttonPane.add(jbReplace);
buttonPane.add(jbReplaceAll);
buttonPane.add(jbCanel);
this.getContentPane().add(contentPane);
this.getContentPane().add(buttonPane);
}
public void actionPerformed(ActionEvent e)
{
String surText=jtFindContent.getText();
if(e.getSource()==jbFindNext)
{
location=area.getText().indexOf(surText,index);//从头开始查找,返回第一个字串所在的索引location
if(location!=-1)
{
area.setSelectionStart(location);
area.setSelectionEnd(location+surText.length());
index=surText.length()+location+1;
}
if(location==-1)
JOptionPane.showMessageDialog(this,"没有找到\""+surText+"\"");
}
if(e.getSource()==jbReplace)
{
location=area.getText().indexOf(surText,index);//从头开始查找,返回第一个字串所在的索引location
if(location!=-1)
{
area.setSelectionStart(location);
area.setSelectionEnd(location+surText.length());
index=surText.length()+location+1;
area.replaceSelection(jtReplaceContent.getText());
}
if(location==-1)
JOptionPane.showMessageDialog(this,"没有找到\""+surText+"\"");
}
if(e.getSource()==jbReplaceAll)
{
while(true)
{
location=area.getText().indexOf(surText,index);//从头开始查找,返回第一个字串所在的索引location
if(location!=-1)
{
area.setSelectionStart(location);
area.setSelectionEnd(location+surText.length());
index=surText.length()+location+1;
area.replaceSelection(jtReplaceContent.getText());
}
if(location==-1)
break;
}
}
if(e.getSource()==jbCanel)
{
this.dispose();
}
}
‘拾’ JAVA记事本 程序代码~
刚才我这登的两号 回答问题出现了碰撞,上面那阿辉的代码接这里!!!import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;public class JNotePadUI extends JFrame {
private JMenuItem menuOpen;
private JMenuItem menuSave;
private JMenuItem menuSaveAs;
private JMenuItem menuClose; private JMenu editMenu;
private JMenuItem menuCut;
private JMenuItem menuCopy;
private JMenuItem menuPaste; private JMenuItem menuAbout;
private JTextArea textArea;
private JLabel stateBar;
private JFileChooser fileChooser;
private JPopupMenu popUpMenu; public JNotePadUI() {
super("新建文本文件");
setUpUIComponent();
setUpEventListener();
setVisible(true);
}
private void setUpUIComponent() {
setSize(640, 480);
// 菜单栏
JMenuBar menuBar = new JMenuBar();
// 设置“文件”菜单
JMenu fileMenu = new JMenu("文件");
menuOpen = new JMenuItem("打开");
// 快捷键设置
menuOpen.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_O,
InputEvent.CTRL_MASK));
menuSave = new JMenuItem("保存");
menuSave.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_S,
InputEvent.CTRL_MASK));
menuSaveAs = new JMenuItem("另存为"); menuClose = new JMenuItem("关闭");
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);