Java记事本源代码(完整)

合集下载

简单记事本java源码实例

简单记事本java源码实例

简单记事本java源码实例本⽂实例讲述了简单记事本java实现代码。

分享给⼤家供⼤家参考。

具体如下:完整代码如下:复制代码代码如下:import java.awt.*;import java.io.*;import java.awt.datatransfer.*;import java.awt.event.*;public class Main extends Frame implements ActionListener {private static final long serialVersionUID = 1L;TextArea textArea = new TextArea();MenuBar menuBar = new MenuBar();Menu fileMenu = new Menu("File");MenuItem newItem = new MenuItem("New");MenuItem openItem = new MenuItem("Open");MenuItem saveItem = new MenuItem("Save");MenuItem saveAsItem = new MenuItem("Save As");MenuItem exitItem = new MenuItem("Exit");Menu editMenu = new Menu("Edit");MenuItem selectItem = new MenuItem("Select All");MenuItem copyItem = new MenuItem("Copy");MenuItem cutItem = new MenuItem("Cut");MenuItem pasteItem = new MenuItem("Paste");String fileName = null;Toolkit toolKit=Toolkit.getDefaultToolkit();Clipboard clipBoard=toolKit.getSystemClipboard();private FileDialog openFileDialog = new FileDialog(this,"Open File",FileDialog.LOAD);private FileDialog saveAsFileDialog = new FileDialog(this,"Save File As",FileDialog.SAVE); public Main(){setTitle("记事本程序-by Jackbase");setFont(new Font("Times New Roman",Font.PLAIN,12));setBackground(Color.white);setSize(400,300);fileMenu.add(newItem);fileMenu.add(openItem);fileMenu.addSeparator();fileMenu.add(saveItem);fileMenu.add(saveAsItem);fileMenu.addSeparator();fileMenu.add(exitItem);editMenu.add(selectItem);editMenu.addSeparator();editMenu.add(copyItem);editMenu.add(cutItem);editMenu.add(pasteItem);menuBar.add(fileMenu);menuBar.add(editMenu);setMenuBar(menuBar);add(textArea);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});newItem.addActionListener(this);openItem.addActionListener(this);saveItem.addActionListener(this);saveAsItem.addActionListener(this);exitItem.addActionListener(this);selectItem.addActionListener(this);copyItem.addActionListener(this);cutItem.addActionListener(this);pasteItem.addActionListener(this);}public void actionPerformed(ActionEvent e) { //监听事件Object eventSource = e.getSource();if(eventSource == newItem){textArea.setText("");}else if(eventSource == openItem){openFileDialog.show();fileName = openFileDialog.getDirectory()+openFileDialog.getFile();if(fileName != null)readFile(fileName);}else if (eventSource == saveItem){if(fileName != null)writeFile(fileName);}else if(eventSource == saveAsItem){saveAsFileDialog.show();fileName = saveAsFileDialog.getDirectory()+saveAsFileDialog.getFile();if (fileName!= null)writeFile(fileName);}else if(eventSource == selectItem){textArea.selectAll();}else if(eventSource == copyItem){String text=textArea.getSelectedText();StringSelection selection=new StringSelection(text);clipBoard.setContents(selection,null);}else if(eventSource == cutItem){String text=textArea.getSelectedText();StringSelection selection=new StringSelection(text);clipBoard.setContents(selection,null);textArea.replaceRange("",textArea.getSelectionStart(),textArea.getSelectionEnd()); }else if(eventSource == pasteItem){Transferable contents=clipBoard.getContents(this);if(contents==null) return;String text;text="";try{text=(String)contents.getTransferData(DataFlavor.stringFlavor);}catch(Exception exception){}textArea.replaceRange(text,textArea.getSelectionStart(),textArea.getSelectionEnd()); }else if(eventSource == exitItem){System.exit(0);}}public void readFile(String fileName){ //读取⽂件处理try{File file = new File(fileName);FileReader readIn = new FileReader(file);int size = (int)file.length();int charsRead = 0;char[] content = new char[size];while(readIn.ready())charsRead += readIn.read(content, charsRead, size - charsRead);readIn.close();textArea.setText(new String(content, 0, charsRead)); }catch(IOException e){System.out.println("Error opening file");}}public void writeFile(String fileName){ //写⼊⽂件处理 try{File file = new File (fileName);FileWriter writeOut = new FileWriter(file);writeOut.write(textArea.getText());writeOut.close();}catch(IOException e){System.out.println("Error writing file");}}@SuppressWarnings("deprecation")public static void main(String[] args){Frame frame = new Main(); //创建对象frame.show(); //是对象显⽰}}运⾏结果如下图所⽰:希望本⽂所述对⼤家的java程序设计有所帮助。

java编写的记事本源代码

java编写的记事本源代码

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.text.*;import javax.swing.event.*;public class IJMFrame extends JFrame {Document document = null;JTextArea textArea = new JTextArea();JScrollPane scrollPane = new JScrollPane(textArea); EditController controller;//------ 定义菜单变量------//JMenuBar menuBar = new JMenuBar();JMenu menuFile = new JMenu("文件");JMenu menuEdit = new JMenu("编辑");JMenu menuFormat = new JMenu("格式"); JPopupMenu memuPopup = new JPopupMenu(); JMenuItem itemNew = new JMenuItem("新建"); JMenuItem itemOpen = new JMenuItem("打开"); JMenuItem itemSave = new JMenuItem("保存"); JMenuItem itemSaveAs = new JMenuItem("另存"); JMenuItem itemExit = new JMenuItem("退出"); JMenuItem itemUndo = new JMenuItem("撤消"); JMenuItem itemCut = new JMenuItem("剪切"); JMenuItem itemCopy = new JMenuItem("复制"); JMenuItem itemPaste = new JMenuItem("粘贴"); JMenuItem itemDelete = new JMenuItem("删除"); JMenuItem itemFind = new JMenuItem("查找"); JMenuItem itemReplace = new JMenuItem("替换"); JMenuItem itemSelectAll = new JMenuItem("全选"); JMenuItem itemFont = new JMenuItem("字体");//------------定义右键菜单------------------------// JMenuItem popupMenu_Undo=new JMenuItem("撤销"); JMenuItem popupMenu_Cut=new JMenuItem("剪切"); JMenuItem popupMenu_Copy=new JMenuItem("复制"); JMenuItem popupMenu_Paste=new JMenuItem("粘贴"); JMenuItem popupMenu_Delete=new JMenuItem("删除"); JMenuItem popupMenu_SelectAll=new JMenuItem("全选");public IJMFrame() {super("记事本");setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setJMenuBar(menuBar);//创建新的菜单栏getContentPane().add(scrollPane);document = textArea.getDocument();textArea.setLineWrap(true);// 默认为换行textArea.setWrapStyleWord(true);//-- 设置菜单--//itemUndo.setEnabled(false);menuBar.add(menuFile);menuBar.add(menuEdit);menuBar.add(menuFormat);menuFile.add(itemNew);menuFile.add(itemOpen);menuFile.add(itemSave);menuFile.add(itemSaveAs);menuFile.addSeparator();menuFile.add(itemExit);menuEdit.add(itemUndo);menuEdit.addSeparator();menuEdit.add(itemCut);menuEdit.add(itemCopy);menuEdit.add(itemPaste);menuEdit.add(itemDelete);menuEdit.addSeparator();menuEdit.add(itemFind);menuEdit.add(itemReplace);menuEdit.add(itemSelectAll);menuFormat.add(itemFont);popupMenu_Undo.setEnabled(false); // 撤消选项初始设为不可用memuPopup.add(popupMenu_Undo);memuPopup.addSeparator();memuPopup.add(popupMenu_Cut);memuPopup.add(popupMenu_Copy);memuPopup.add(popupMenu_Paste);memuPopup.add(popupMenu_Delete);memuPopup.addSeparator();memuPopup.add(popupMenu_SelectAll);//-- 增加菜单的侦听者--//controller = new EditController(this);itemNew.addActionListener(controller);itemOpen.addActionListener(controller);itemSave.addActionListener(controller);itemSaveAs.addActionListener(controller);itemExit.addActionListener(controller);itemUndo.addActionListener(controller);itemCut.addActionListener(controller);itemCopy.addActionListener(controller);itemPaste.addActionListener(controller);itemDelete.addActionListener(controller);itemFind.addActionListener(controller);itemReplace.addActionListener(controller);itemSelectAll.addActionListener(controller);itemFont.addActionListener(controller);popupMenu_Undo.addActionListener(controller);popupMenu_Cut.addActionListener(controller);popupMenu_Copy.addActionListener(controller);popupMenu_Paste.addActionListener(controller);popupMenu_Delete.addActionListener(controller);popupMenu_SelectAll.addActionListener(controller);document.addDocumentListener(controller);document.addUndoableEditListener(controller);addWindowListener(controller);MouseAdapter mAdapter=new MouseAdapter(){public void mousePressed(MouseEvent e) {checkForTriggerEvent(e);}public void mouseReleased(MouseEvent e) {checkForTriggerEvent(e);}private void checkForTriggerEvent(MouseEvent e) {if (e.isPopupTrigger())memuPopup.show(e.getComponent(), e.getX(), e.getY());// 在组件调用者的坐标空间中的位置// X、Y// 显示弹出菜单。

java编程 记事本 代码

java编程 记事本 代码
private JMenu helpMenu = new JMenu();
// 构造函数
public Notepad(){
initComponents();
}
private void initComponents(){
// 添加子菜单项到文件菜单
fileMenu.setText("\u6587\u4ef6 (F)");
pane.add("Center",scroll);
setContentPane(pane);
}
// 定义新建菜单项方法
public void newMenuItemActionPerformed(ActionEvent evt){
file = null;
if(!("".equals(content.getText()))){
pageSetupMenuItem.setText(" 页面设置(U)...");
printMenuItem.setText(" 打印(P)... Ctrl+P");
exitMenuItem.setText(" 退出");
fileMenu.add(newMenuItem);
private JMenuItem saveMenuItem = new JMenuItem();
private JMenuItem saveAsMenuItem = new JMenuItem();
private JMenuItem pageSetupMenuItem = new JMenuItem();
newMenuItem.setText(" 新建(N) Ctrl+N");

记事本Java源程序

记事本Java源程序
return chooser.getSelectedFile();
}
return null;
}
});
jmiNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JColorChooser;
return f.isDirectory()
|| filename.endsWith(".txt")
|| filename.endsWith(".cpp")
|| filename.endsWith(".c")
|| filename.endsWith(".java");
return "文本文件";
}
@Override
public boolean accept(File f) { // 判断文件是否被选择在chooser.showOpenDialog()里
String filename = f.getName().toLowerCase();
}
Байду номын сангаас });
int chooserVar = chooser.showOpenDialog(new JFrame());

记事本程序源代码汇总

记事本程序源代码汇总

import java.awt.event.*;import java.awt.*;import java.io.*;import ng.String;class jsb implements ActionListener{Dialog bb;String strt;int i;FileDialog fd;File file;public Frame f;public TextArea p1;public MenuBar menubar;public Menu menu1,menu2,menu3;public MenuItem item1,item2,item3,item4,item5,item6,item7,item8,item9,item10; jsb(String s{ i=0;f=new Frame(s;p1=new TextArea("";f.setSize(500,500;f.setBackground(Color.white;f.setVisible(true;menubar=new MenuBar(;menu1=new Menu("文件";menu2=new Menu("编辑";menu3=new Menu("帮助";item1=new MenuItem("新建";item2=new MenuItem("打开";item3=new MenuItem("保存";item4=new MenuItem("另存为";item5=new MenuItem("退出";item6=new MenuItem("全选";item7=new MenuItem("复制";item8=new MenuItem("剪切";item9=new MenuItem("粘贴";item10=new MenuItem("关于";f.addWindowListener(new WindowAdapter({public void windowClosing(WindowEvent e {f.setVisible(false;System.exit(0;}};menu1.add(item1;menu1.add(item2;menu1.add(item3;menu1.add(item4;menu1.add(item5;menu2.add(item6;menu2.add(item7;menu2.add(item8;menu2.add(item9;menu3.add(item10;menubar.add(menu1;menubar.add(menu2;menubar.add(menu3;f.setMenuBar(menubar;item1.addActionListener(this;item2.addActionListener(this;item3.addActionListener(this;item4.addActionListener(this;item5.addActionListener(this;item6.addActionListener(this;item7.addActionListener(this;item8.addActionListener(this;item9.addActionListener(this;item10.addActionListener(this;f.setLayout(new GridLayout(1,1;f.add(p1;f.pack(;}public void actionPerformed(ActionEvent e { String ss;ss=p1.getText(.trim(;if (e.getSource(==item5{if (i==0 &&(ss.length(!=0{bc(;}else{System.exit(0;}}if (e.getSource(==item1{if (i==0&&(ss.length(!=0{bc(;}else{p1.setText("";i=0;f.setTitle("文件对话框"; } }if (e.getSource(==item2{fd=new FileDialog(f,"打开文件",0;fd.setVisible(true;try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"文件对话框"; FileReader fr=new FileReader(file; BufferedReader br=new BufferedReader(fr; String line = null;String view = "";while((line=br.readLine(!=null{view += line+"\n";}p1.setText(view;br.close(;fr.close(;}catch(IOException expIn{}}if (e.getSource(==item3{if (i==0{bc(;}else{try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"--记事本";FileWriter fw=new FileWriter(file; BufferedWriter bw=new BufferedWriter(fw; String s =p1.getText(;s = s.replaceAll("\n","\r\n";bw.write(s;bw.flush(;bw.close(;fw.close(;i=1;}catch(IOException expOut{i=0;}}}if (e.getSource(==item4{bc(;}if (e.getSource(==item10{bb=new Dialog(f,"关于";Label l1=new Label("本记事本的完成感谢老师和同学的帮助!!"; bb.add(l1; bb.setSize(250,150;bb.setBackground(Color.white;bb.show(;bb.addWindowListener(new WindowAdapter({public void windowClosing(WindowEvent e{bb.setVisible(false;bb.dispose(;}};}if (e.getSource(==item6{p1.setSelectionStart(0;p1.setSelectionEnd(p1.getText(.length(; }if (e.getSource(==item7{try{String str=p1.getSelectedText(;if(str.length(!=0{strt=str;}}catch(Exception ex{}}if (e.getSource(==item8{try{String str=p1.getSelectedText(;if(str.length(!=0{p1.replaceRange("",p1.getSelectionStart(,p1.getSelectionEnd(; } }catch(Exception ex{}}if (e.getSource(==item9{if(strt.length(>0{p1.insert(strt,p1.getCaretPosition(;}}}public void bc({fd=new FileDialog(f,"保存文件",1;fd.setVisible(true;try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"--记事本"; FileWriter fw=new FileWriter(file; BufferedWriter bw=new BufferedWriter(fw; String s =p1.getText(;s = s.replaceAll("\n","\r\n";bw.write(s;bw.flush(;bw.close(;fw.close(;i=1;}catch(IOException expOut{}} } public class EX0101 { public static void main(String args[] {jsb dd=new jsb("我的记事本";} }。

Java记事本源代码(完整)

Java记事本源代码(完整)

/*** 作品:记事本* 作者:**** 功能:简单的文字编辑*/import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;class NotePad extends JFrame{private JMenuBar menuBar;private JMenu fielMenu,editMenu,formMenu,aboutMenu;private JMenuItemnewMenuItem,openMenuItem,saveMenuItem,exitMenuItem;private JMenuItemcutMenuItem,copyMenuItem,pasteMenuItem,foundItem,replaceItem,s electAll;private JMenuItem font,about;private JTextArea textArea;private JFrame foundFrame,replaceFrame;private JCheckBoxMenuItem wrapline;private JTextField textField1=new JTextField(15);private JTextField textField2=new JTextField(15);private JButton startButton,replaceButton,reallButton;int start=0;String value;File file=null;JFileChooser fileChooser=new JFileChooser();boolean wrap=false;public NotePad(){//创建文本域textArea=new JTextArea();add(new JScrollPane(textArea),BorderLayout.CENTER);//创建文件菜单及文件菜单项fielMenu=new JMenu("文件");fielMenu.setFont(new Font("微软雅黑",0,15));newMenuItem=new JMenuItem("新建",newImageIcon("icons\\new24.gif"));newMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_N,InputEvent.CTRL_MASK));newMenuItem.addActionListener(listener);openMenuItem=new JMenuItem("打开",newImageIcon("icons\\open24.gif"));openMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_O,InputEvent.CTRL_MASK));openMenuItem.addActionListener(listener);saveMenuItem=new JMenuItem("保存",newImageIcon("icons\\save.gif"));saveMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_S,InputEvent.CTRL_MASK));saveMenuItem.addActionListener(listener);exitMenuItem=new JMenuItem("退出",newImageIcon("icons\\exit24.gif"));exitMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_E,InputEvent.CTRL_MASK));exitMenuItem.addActionListener(listener);//创建编辑菜单及菜单项editMenu=new JMenu("编辑");editMenu.setFont(new Font("微软雅黑",0,15));cutMenuItem=new JMenuItem("剪切",newImageIcon("icons\\cut24.gif"));cutMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_X,InputEvent.CTRL_MASK));cutMenuItem.addActionListener(listener);copyMenuItem=new JMenuItem("复制",newImageIcon("icons\\copy24.gif"));copyMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_C,InputEvent.CTRL_MASK));copyMenuItem.addActionListener(listener);pasteMenuItem=new JMenuItem("粘贴",newImageIcon("icons\\paste24.gif"));pasteMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEven t.VK_V,InputEvent.CTRL_MASK));pasteMenuItem.addActionListener(listener);foundItem=new JMenuItem("查找");foundItem.setFont(new Font("微软雅黑",Font.BOLD,13));foundItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _F,InputEvent.CTRL_MASK));foundItem.addActionListener(listener);replaceItem=new JMenuItem("替换");replaceItem.setFont(new Font("微软雅黑",Font.BOLD,13));replaceItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_R,InputEvent.CTRL_MASK));replaceItem.addActionListener(listener);selectAll=new JMenuItem("全选");selectAll.setFont(new Font("微软雅黑",Font.BOLD,13));selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _A,InputEvent.CTRL_MASK));selectAll.addActionListener(listener);//创建格式菜单及菜单项formMenu=new JMenu("格式");formMenu.setFont(new Font("微软雅黑",0,15));wrapline=new JCheckBoxMenuItem("自动换行");wrapline.setFont(new Font("微软雅黑",Font.BOLD,13));wrapline.addActionListener(listener);wrapline.addChangeListener(new ChangeListener() {public void stateChanged(ChangeEvent e) {if(wrapline.isSelected()){textArea.setLineWrap(true);}elsetextArea.setLineWrap(false);}});font=new JMenuItem("字体");font.setFont(new Font("微软雅黑",Font.BOLD,13)); font.addActionListener(listener);//创建关于菜单aboutMenu=new JMenu("关于");aboutMenu.setFont(new Font("微软雅黑",0,15)); about=new JMenuItem("记事本……");about.setFont(new Font("微软雅黑",Font.BOLD,13)); about.addActionListener(listener);//添加文件菜单项fielMenu.add(newMenuItem);fielMenu.add(openMenuItem);fielMenu.add(saveMenuItem);fielMenu.addSeparator();fielMenu.add(exitMenuItem);//添加编辑菜单项editMenu.add(cutMenuItem);editMenu.add(copyMenuItem);editMenu.add(pasteMenuItem);editMenu.add(foundItem);editMenu.add(replaceItem);editMenu.addSeparator();editMenu.add(selectAll);//添加格式菜单项formMenu.add(wrapline);formMenu.add(font);//添加关于菜单项aboutMenu.add(about);//添加菜单menuBar=new JMenuBar();menuBar.add(fielMenu);menuBar.add(editMenu);menuBar.add(formMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//创建两个框架,用作查找和替换foundFrame=new JFrame();replaceFrame=new JFrame();//创建两个文本框textField1=new JTextField(15);textField2=new JTextField(15);startButton=new JButton("开始");startButton.addActionListener(listener);replaceButton=new JButton("替换为");replaceButton.addActionListener(listener);reallButton=new JButton("全部替换");reallButton.addActionListener(listener);}//创建菜单项事件监听器ActionListener listener=new ActionListener() {public void actionPerformed(ActionEvent e) {String name=e.getActionCommand();if(e.getSource() instanceof JMenuItem){if("新建".equals(name)){textArea.setText("");file=null;}if("打开".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}intreturnVal=fileChooser.showOpenDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileReader reader=new FileReader(file);int len=(int)file.length();char[] array=new char[len];reader.read(array,0,len);reader.close();textArea.setText(new String(array));}catch(Exception e_open){e_open.printStackTrace();}}}if("保存".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}intreturnVal=fileChooser.showSaveDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileWriter writer=new FileWriter(file);writer.write(textArea.getText());writer.close();}catch (Exception e_save) {e_save.getStackTrace();}}if("退出".equals(name)){System.exit(0);}if("剪切".equals(name)){textArea.cut();}if("复制".equals(name)){textArea.copy();}if("粘贴".equals(name)){textArea.paste();}if("查找".equals(name)){value=textArea.getText();foundFrame.add(textField1,BorderLayout.CENTER);foundFrame.add(startButton,BorderLayout.SOUTH);foundFrame.setLocation(300,300);foundFrame.setTitle("查找");foundFrame.pack();foundFrame.setVisible(true);foundFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );}if("替换".equals(name)){value=textArea.getText();JLabel label1=new JLabel("查找内容:");JLabel label2=new JLabel("替换为:");JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(2,2));JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,3));replaceFrame.add(panel1,BorderLayout.NORTH);replaceFrame.add(panel2,BorderLayout.CENTER);panel1.add(label1);panel1.add(textField1);panel1.add(label2);panel1.add(textField2);panel2.add(startButton);panel2.add(replaceButton);panel2.add(reallButton);replaceFrame.setTitle("替换");replaceFrame.setLocation(300,300);replaceFrame.pack();replaceFrame.setVisible(true);replaceFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLO SE);}if("开始".equals(name)||"下一个".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;startButton.setText("下一个");}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif"));foundFrame.dispose();}}if("替换为".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;textArea.replaceSelection(textField2.getText());}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif"));foundFrame.dispose();}}if("全部替换".equals(name)){String temp=textArea.getText();temp=temp.replaceAll(textField1.getText(),textField2.getTex t());textArea.setText(temp);}if("全选".equals(name)){textArea.selectAll();}if("字体".equals(name)){FontDialog fontDialog=newFontDialog(NotePad.this);fontDialog.setVisible(true);if(textArea.getFont()!=fontDialog.getFont()){textArea.setFont(fontDialog.getFont());}}if("记事本……".equals(name)){AboutDialog aboutDialog=newAboutDialog(NotePad.this);aboutDialog.setVisible(true);}}};//创建字体设置对话面板,并添加相应事件监听器class FontDialog extends JDialog implements ItemListener, ActionListener, WindowListener{public JCheckBox Bold=new JCheckBox("Bold",false);public JCheckBox Italic=new JCheckBox("Italic",false);public List Size,Name;public int FontName;public int FontStyle;public int FontSize;public JButton OK=new JButton("OK");public JButton Cancel=new JButton("Cancel");public JTextArea Text=new JTextArea("字体预览文本域\n0123456789\nAaBbCcXxYyZz");public FontDialog(JFrame owner) {super(owner,"字体设置",true);GraphicsEnvironmentg=GraphicsEnvironment.getLocalGraphicsEnvironment();String name[]=g.getAvailableFontFamilyNames();Name=new List();Size=new List();FontName=0;FontStyle=0;FontSize=8;int i=0;Name.add("Default Value");for(i=0;i<name.length;i++)Name.add(name[i]);for(i=8;i<257;i++)Size.add(String.valueOf(i));this.setLayout(null);this.setBounds(250,200,480, 306);this.setResizable(false);OK.setFocusable(false);Cancel.setFocusable(false);Bold.setFocusable(false);Italic.setFocusable(false);Name.setFocusable(false);Size.setFocusable(false);Name.setBounds(10, 10, 212, 259);this.add(Name);Bold.setBounds(314, 10, 64, 22);this.add(Bold);Italic.setBounds(388, 10, 64, 22);this.add(Italic);Size.setBounds(232, 10, 64, 259);this.add(Size);Text.setBounds(306, 40, 157, 157);this.add(Text);OK.setBounds(306, 243, 74, 26);this.add(OK);Cancel.setBounds(390, 243, 74, 26);this.add(Cancel);Name.select(FontName);Size.select(FontSize);Text.setFont(getFont());Name.addItemListener(this);Size.addItemListener(this);Bold.addItemListener(this);Italic.addItemListener(this);OK.addActionListener(this);Cancel.addActionListener(this);this.addWindowListener(this);}public void itemStateChanged(ItemEvent e) {Text.setFont(getFont());}public void actionPerformed(ActionEvent e) {if(e.getSource()==OK){FontName=Name.getSelectedIndex();FontStyle=getStyle();FontSize=Size.getSelectedIndex();this.setVisible(false);}else cancel();}public void windowClosing(WindowEvent e) {cancel();}public Font getFont(){if(Name.getSelectedIndex()==0) return new Font("新宋体",getStyle(),Size.getSelectedIndex()+8);else return newFont(Name.getSelectedItem(),getStyle(),Size.getSelectedIndex() +8);}public void cancel(){Name.select(FontName);Size.select(FontSize);setStyle();Text.setFont(getFont());this.setVisible(false);}public void setStyle(){if(FontStyle==0 || FontStyle==2)Bold.setSelected(false);else Bold.setSelected(true);if(FontStyle==0 || FontStyle==1)Italic.setSelected(false);else Italic.setSelected(true);}public int getStyle(){int bold=0,italic=0;if(Bold.isSelected()) bold=1;if(Italic.isSelected()) italic=1;return bold+italic*2;}public void windowActivated(WindowEvent arg0) {}public void windowClosed(WindowEvent arg0) {}public void windowDeactivated(WindowEvent arg0) {}public void windowDeiconified(WindowEvent arg0) {}public void windowIconified(WindowEvent arg0) {}public void windowOpened(WindowEvent arg0) {} }//创建关于对话框class AboutDialog extends JDialog implements ActionListener{ public JButton OK,Icon;public JLabel Name,Version,Author,Java;public JPanel Panel;AboutDialog(JFrame owner) {super(owner,"关于",true);OK=new JButton("OK");Icon=new JButton(new ImageIcon("icons\\edit.gif"));Name=new JLabel("Notepad");Version=new JLabel("Version 1.0");Java=new JLabel("JRE Version 6.0");Author=new JLabel("Copyright (c) 11-5-2012 By Jianmin Chen");Panel=new JPanel();Color c=new Color(0,95,191);Name.setForeground(c);Version.setForeground(c);Java.setForeground(c);Author.setForeground(c);Panel.setBackground(Color.white);OK.setFocusable(false);this.setBounds(250,200,280, 180);this.setResizable(false);this.setLayout(null);Panel.setLayout(null);OK.addActionListener(this);Icon.setFocusable(false);Icon.setBorderPainted(false);Author.setFont(new Font(null,Font.PLAIN,11));Panel.add(Icon);Panel.add(Name);Panel.add(Version);Panel.add(Author);Panel.add(Java);this.add(Panel);this.add(OK);Panel.setBounds(0, 0, 280, 100);OK.setBounds(180, 114, 72, 26);Name.setBounds(80, 10, 160, 20);Version.setBounds(80, 27, 160, 20);Author.setBounds(15, 70, 250, 20);Java.setBounds(80, 44, 160, 20);Icon.setBounds(16, 14, 48, 48);}public void actionPerformed(ActionEvent e) { this.setVisible(false);}}}//创建记事本public class ChenJianmin {public static void main(String[] args){EventQueue.invokeLater(new Runnable() {public void run() {NotePad notePad=new NotePad();notePad.setTitle("记事本");notePad.setVisible(true);notePad.setBounds(100,100,800,600);notePad.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}});}}。

Java记事本源代码

Java记事本源代码

import java.awt.*;import java.awt.event.*;import java.text.*;import java.util.*;import java.io.*;import javax.swing.*;import javax.swing.event.*;import java.util.List;public class TextFileEditorJFrame extends JFrame implementsActionListener,ItemListener,MouseListener{private File file; // 当前文件//--- 文件菜单,定义的添加项,新建,打开,保存,另存为,退出--- // private JMenuItemmenuitem_create,menuitem_open,menuitem_save,menuitem_saveas,menuitem_exit;//--- 编辑菜单,定义的添加项,剪切,复制,粘贴,删除--- //private JMenuItem menuitem_cut, menuitem_copy,menuitem_paste,menuitem_delete;// - 右键菜单项,剪切,复制,粘贴,删除--- //private JMenuItem final_cut,final_copy,final_paste,final_delete;private JTextArea textarea;private JButton button_color;private JScrollPane scroll;private JDialog dialog1,dialog2;private JLabel label_dialog,label_dialog2;II文本编辑区II设置颜色II为文本编辑区提供滚动条II对话框private Boolean via=false; privateJPopupMenu popupmenu; 〃右键弹出菜单private JCheckBoxMenuItem checkbox_cuti, checkbox_xieti; //复选框表示粗体、斜体private String fileName=null; // 文件名private int k = 0; //k 用来存放字号大小private String size = " 宋体";private JComboBox jco1,jco2; //工具栏处表示字体,字号组合框File currentFile,saveFileName = null, fileName1 = null; //文件类public TextFileEditorJFrame() // 空文件的构造方法,初始化{super(”文本编辑器”);II框架的标题this.setSize(700,500);this.setLocatio n(140,140); II 相对界面的位置this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textarea = new JTextArea(""); textarea.addMouseListener(this);this.add(textarea); this.addMenu(); this.addToolBar();II添加文本区〃调用自定义的addMe nu()方法,添加菜单栏II调用自定义的addToolBar ()方法,添加工具栏textarea.setFont(new Font("宋体",1,16)); II 设置文本区初始字体this.setVisible(true); textarea.requestFocus(); this.file = null; this(); if (file!=null){this.file = file;this.setTitle(this.file.getName()); // 把标题设置成得到的文件名, 通过文件对象 调用函数得到文件名this.textarea.setText(this.readFromFile()); // 调用 readFromFile() 方法,把读取的内 容在文本区显示}}private void addMenu()// 添加主菜单{JMenuBar menubar = new JMenuBar(); //创建菜单栏 this.setJMenuBar(menubar);//将菜单条设置为当前窗口的菜单条// --------------------------- 文件菜单 ----------------------------- JMenu menu_file = new JMenu(" 文件 "); menubar.add(menu_file);// 创建文件菜单,并添加到菜单栏menuitem_create = new JMenuItem(" 新建 (N)"); // 创建新建菜单项 menuitem_create.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK)); //为新建设置快捷键 Ctrl+Nmenu_file.add(menuitem_create);//添加到文件菜单menuitem_create.addActionListener(this);//设置文本区焦聚空文件对象}public TextFileEditorJFrame(String filename)文件内容{this();if (filename!=null){this.file = new File(filename); this.setTitle(filename);栏上this.textarea.setText(this.readFromFile());示在文本区中}}public TextFileEditorJFrame(File file){名,从而读取文件内容//指定文件名的构造方法//即打开文件后显示//将文件名添加在窗口标题读取指定文件中的字符串,并// 指定文件对象的构造方法 , //通过文件对象调用函数得到文menuitem_open = new JMenuItem(" 打开(O)"); // 创建打开菜单项menuitem_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,ActionEvent.CTRL_MASK)); //为打开设置快捷键Ctrl+Omenu_file.add(menuitem_open); // 添加到文件菜单menuitem_open.addActionListener(this);menuitem_save = new JMenuItem(" 保存(S)");// 创建保存菜单项menuitem_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK));// 为保存设置快捷键Ctrl+Smenu_file.add(menuitem_save); // 添加到文件菜单menuitem_save.addActionListener(this);menuitem_saveas = new JMenuItem(" 另存为(F12)");// 创建另存为菜单项menuitem_saveas.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F12,ActionEvent.CTRL_MASK));// 为另存为设置快捷键Ctrl+F12menu_file.add(menuitem_saveas); // 添加到文件菜单menuitem_saveas.addActionListener(this);menu_file.addSeparator(); //在菜单中添加分隔线,将菜单项进行分组menuitem_exit = new JMenuItem(" 退出(E)");// 创建退出菜单项menuitem_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,ActionEvent.ALT_MASK));// 为退出设置快捷键Ctrl+Emenu_file.add(menuitem_exit);// 添加到文件菜单menuitem_exit.addActionListener(this);// --------------------------- 编辑菜单-----------------------------JMenu menu_edit = new JMenu(" 编辑"); //创建编辑菜单,添加到菜单栏menubar.add(menu_edit);menuitem_cut = new JMenuItem(" 剪切(X)");// 创建剪切菜单项,并添加到编辑菜单中menuitem_cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,ActionEvent.CTRL_MASK));// 设置快捷键Ctrl+Xmenu_edit.add(menuitem_cut);menuitem_cut.addActionListener(this);menuitem_copy = new JMenuItem(" 复制(C)");// 在编辑菜单中添加复制菜单项menuitem_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK));// 设置快捷键Ctrl+Cmenu_edit.add(menuitem_copy); menuitem_copy.addActionListener(this);menuitem_paste = new JMenuItem(" 粘贴(V)");// 创建粘贴menuitem_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V ,ActionEvent.CTRL_M ASK));// 设置快捷键Ctrl+Vmenu_edit.add(menuitem_paste); menuitem_paste.addActionListener(this);menuitem_delete = new JMenuItem(" 删除(D)");// 创建删除menuitem_delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,ActionEvent.CTRL_ MASK));// 设置快捷键Ctrl+Dmenu_edit.add(menuitem_delete); menuitem_delete.addActionListener(this);menu_edit.addActionListener(new ActionListener() // 注册事件监听{ public void actionPerformed(ActionEvent e) { checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性}});menu_edit.addSeparator(); //设置分隔线// --------------------------- 格式菜单-----------------------------JMenu menu_style = new JMenu(" 格式"); //在菜单栏中创建格式菜单menubar.add(menu_style);JMenu menu_ziti = new JMenu(" 字体"); // 添加字体项checkbox_cuti=newJCheckBoxMenuItem(" 粗体"); checkbox_xieti=new JCheckBoxMenuItem(" 斜体");checkbox_cuti.addItemListener(this); checkbox_xieti.addItemListener(this);menu_ziti.add(checkbox_cuti); // 粗体,斜体复选菜单添加到字体项中menu_ziti.add(checkbox_xieti);menu_style.add(menu_ziti);JMenuItem menu_color = new JMenuItem(" 颜色"); // 添加颜色项menu_style.add(menu_color);menu_color.addActionListener(this);// --------------------------- 帮助菜单JMenu menu_help = new JMenu(" 帮助");//创建帮助菜单menubar.add(menu_help);JMenuItem menu_look = new JMenuItem(" 查看帮助(L)"); //帮助菜单中添加帮助查看项menu_help.add(menu_look); menu_look.addActionListener(this);JMenuItem menu_about = new JMenuItem(" 关于文本(A)");// 添加关于文本项menu_help.add(menu_about);menu_about.addActionListener(this);dialog1 = new JDialog(this," 关于文本"); // 单击关于文本,弹出对话框dialog1.setSize(480,150);label_dialog = new JLabel("--- 作者:郑健健,制作时间:2013,1,8------------ ",JLabel.CENTER);dialog1.add(label_dialog); dialog1.setDefaultCloseOperation(HIDE_ON_CLOSE);dialog2 = new JDialog(this," 帮助文档");// 单击查看帮助,弹出对话框dialog2.setSize(500,220);label_dialog2 = new JLabel(" ----- 欢迎使用记事本---- ",JLabel.CENTER);dialog2.add(label_dialog2);dialog2.setDefaultCloseOperation(HIDE_ON_CLOSE);// ------------------------------- 右键弹出菜单对象popupmenu = new JPopupMenu(); final_cut = new JMenuItem(" 剪切(X)"); //final_cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));// 设置快捷键Ctrl+Xpopupmenu.add(final_cut); // 添加剪切final_cut.addActionListener(this);final_copy = new JMenuItem(" 复制(C)");final_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK)) ;//设置快捷键Ctrl+Cpopupmenu.add(final_copy); // 添加复制final_copy.addActionListener(this);final_paste = new JMenuItem(" 粘贴(V)");final_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V ,InputEvent.CTRL_MASK)) ;//设置快捷键Ctrl+Vpopupmenu.add(final_paste); //添加粘贴final_paste.addActionListener(this);final_delete = new JMenuItem(" 删除(D)");final_delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,InputEvent.CTRL_MASK) );// 设置快捷键Ctrl+Dpopupmenu.add(final_delete); // 添加删除final_delete.addActionListener(this);textarea.add(popupmenu);// ------------ 文本编辑区注册右键菜单事件------- //textarea.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e){ checkForTriggerEvent(e);} public void mouseReleased(MouseEvent e) { checkForTriggerEvent(e);}private void checkForTriggerEvent(MouseEvent e) {if (e.isPopupTrigger()) {popupmenu.show(e.getComponent(), e.getX(), e.getY());// X 、Y // 显示弹出菜单}// 在组件调用者的坐标空间中的位置checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性textarea.requestFocus(); // 编辑区获取焦点}});Container container = getContentPane(); // 创建滚动条container.setLayout(newBorderLayout() );scroll = new JScrollPane( textarea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS ); container.add( scroll, BorderLayout.CENTER );}private void addToolBar()// --------------- 设置工具栏-------------------- //JToolBar jto=new JToolBar(); // 创建工具栏jto.setBackground(Color.black); //设置工具栏背景颜色JButton btziti=new JButton("字体");jto.add(btziti); // 添加显示字体的按钮Stringob1[]=GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();// 字体组合框数据项String ob2[]={"10","12","14","16","18","20","24","28","32","36","48","72"};// 字号组合框数据项jco1=new JComboBox(ob1);// 两个组合框:字体,字号大小jco2=new JComboBox(ob2);jco1.addActionListener(this);jco2.addActionListener(this);jto.add(jco1); //工具栏里面添加:字体,字号组合框jto.add(jco2);this.add(jto,BorderLayout.NORTH);// 添加工具栏}public void checkMenuItemEnabled(){String selectText = textarea.getSelectedText();if (selectText == null){ // 如果没有选择文本,剪切,删除,复制功能不可用menuitem_cut.setEnabled(false); final_cut.setEnabled(false);menuitem_copy.setEnabled(false); final_copy.setEnabled(false);menuitem_delete.setEnabled(false); final_delete.setEnabled(false);}else{ // 选择了文本,剪切,删除,复制功能可用menuitem_cut.setEnabled(true);final_cut.setEnabled(true); menuitem_copy.setEnabled(true);final_copy.setEnabled(true); menuitem_delete.setEnabled(true);final_delete.setEnabled(true);}}public String readFromFile() //使用流从指定文本文件中读取字符串try {FileReader fin = new FileReader(this.file); // 以文件对象作为文件名来读取文件BufferedReader bin = new BufferedReader(fin); // 设置缓冲区,将读到的字符串暂存在缓冲区String aline="", lines="";do{aline = bin.readLine(); // 读取一行字符串,抵达文件结尾时返回nullif (aline!=null)lines += aline + "\r\n";} while (aline!=null); // 文件不为空一直读取bin.close(); //读取后关闭文件,释放缓冲区fin.close();return lines;}catch (IOException ioex){return null; // 出现异常,返回空}}public boolean openDialog() //执行打开文件对话框{ // 在打开文件对话框中,单击【打开】按钮时返回true,单击【取消】按钮时返回falseFileDialog filedialog = new FileDialog(this," 打开",FileDialog.LOAD); // 创建打开文件对话框filedialog.setVisible(true); // 显示打开文件对话框if ((filedialog.getDirectory()!=null) && (filedialog.getFile()!=null)) // 单击【打开】按钮时,文件路径不为空,文件名不为空{this.file = new File(filedialog.getDirectory(), filedialog.getFile());return true;}elsereturn false; //单击【取消】按钮时}public void fileSaveAs()JFileChooser jFileChooser=new JFileChooser();if(JFileChooser.APPROVE_OPTION==jFileChooser.showSaveDialog(this))// 打开保存对话框,选择yes or no{ fileName=(jFileChooser.getSelectedFile()+".txt");// 文件名称赋给fileNamefileSave(); //fileName 不为空,调用保存函数,对文件进行另存}}public void fileSave(){if(fileName==null){fileSaveAs();}else{if(!via){if(fileName.length()!=0){try{File saveFile=new File(fileName); FileWriter fw=newFileWriter(saveFile); fw.write(textarea.getText()); // 文本内容输出fw.close();via=true;this.setTitle(fileName.substring(stIndexOf("\\")+1));this.repaint();}catch(Exception e){ JOptionPane.showMessageDialog(this," 保存文件时出错"," 错误",JOptionPane.ERROR_MESSAGE);// 提示错误}}else{ fileSaveAs();} }}}public void chooseColor() {Color bcolor=textarea.getForeground(); JColorChooser jColor=new JColorChooser();jColor.setColor(bcolor);textarea.setForeground(JColorChooser.showDialog(textarea," 选择颜色",bcolor));}public void actionPerformed(ActionEvent e) // 单击事件处理程序{if (e.getActionCommand()==" 新建(N)") //单击新建时,弹出提示框,文件是否保存{textarea.replaceRange("", 0, textarea.getText().length()); this.setTitle(" 无标题- 记事本");}if(e.getActionCommand()==" 打开(O)") //单击打开时,弹出对话框{if (this.openDialog()) // 打开文件对话框并单击【打开】按钮时执行,单击【取消】按钮时不执行{this.setTitle(this.file.getName()); // 取得文件名,作为标题this.textarea.setText(this.readFromFile());// 调用读函数,把文件读出,显示到文本区}}if(e.getActionCommand()==" 保存(S)" ) //非第 1 次保存时,只保存不需要打开保存文件对话框{this.fileSave();}if((e.getActionCommand()==" 保存(S)" && this.file==null) ||e.getActionCommand()==" 另存为(F12)"){ // 第 1 次保存或执行"另存为" 菜单时,需要打开保存文件对话框this.fileSaveAs();}if (e.getSource() == menuitem_exit) {int exitChoose = JOptionPane.showConfirmDialog(this, " 确定要退出吗?", " 退出提示", JOptionPane.OK_CANCEL_OPTION);if (exitChoose == JOptionPane.OK_OPTION) {System.exit(0);} else {return;}if(e.getActionCommand()==" 剪切(T)") textarea.cut();if(e.getActionCommand()==" 复制(C)") textarea.copy();if(e.getActionCommand()==" 粘贴(V)") textarea.paste();if(e.getActionCommand()==" 删除(D)"){ textarea.replaceRange("",textarea.getSelectionStart(),textarea.getSelectionEnd());via=false;}if(e.getActionCommand()==" 颜色"){ chooseColor();}if(e.getActionCommand() == " 查看帮助(L)"){ dialog2.setLocation(250,330); dialog2.setVisible(true);}if(e.getActionCommand() == " 关于文本(A)"){ dialog1.setLocation(250,330); dialog1.setVisible(true);}int style=textarea.getFont().getStyle();if(e.getSource()==jco1||e.getSource()== jco2)// 字体和字号组合框的实现{size=(String) jco1.getSelectedItem();k=Integer.parseInt(jco2.getSelectedItem().toString()); textarea.setFont(newFont(size,Font.PLAIN,k));}}public void itemStateChanged(ItemEvent e) // 复选框选择事件处理程序{ // 实现ItemListener 接口中的方法Font font = textarea.getFont(); int style = font.getStyle();if (e.getSource()==checkbox_cuti)style = style A 1;//整数的位运算,异或Aif (e.getSource()==checkbox_xieti) style = style A 2;textarea.setFont(new Font(font.getName(),style,font.getSize()));}public void mouseClicked(MouseEvent mec) //单击鼠标时触发{ // 实现MouseListener 接口中的方法if (mec.getModifiers()==mec.BUTTON3_MASK)/ /单击的是鼠标右键popupmenu.show(textarea,mec.getX(),mec.getY()); //在鼠标单击处显示快捷菜单}public void mousePressed(MouseEvent mep) { }public void mouseReleased(MouseEvent mer) { }public void mouseEntered(MouseEvent mee) { }public void mouseExited(MouseEvent mex) { }public void mouseDragged(MouseEvent med) { }public static void main(String arg[]){new TextFileEditorJFrame();程序在保存功能上有些欠缺,整体可以作为参考。

用Java实现日历记事本源代码

用Java实现日历记事本源代码

CalendarPad类import java.util.Calendar;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import java.util.Hashtable;public class CalendarPad extends JFrame implements MouseListener{int year,month,day;Hashtable hashtable;File file;JTextField showDay[];JLabel title[];Calendar 日历;int 星期几;NotePad notepad=null;Month 负责改变月;Year 负责改变年;String 星期[]={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; JPanel leftPanel,rightPanel;public CalendarPad(int year,int month,int day){leftPanel=new JPanel();JPanel leftCenter=new JPanel();JPanel leftNorth=new JPanel();leftCenter.setLayout(new GridLayout(7,7));rightPanel=new JPanel();this.year=year;this.month=month;this.day=day;负责改变年=new Year(this);负责改变年.setYear(year);负责改变月=new Month(this);负责改变月.setMonth(month);title=new JLabel[7];showDay=new JTextField[42];for(int j=0;j<7;j++){title[j]=new JLabel();title[j].setText(星期[j]);title[j].setBorder(BorderFactory.createRaisedBevelBorder());leftCenter.add(title[j]);}title[0].setForeground(Color.red);title[6].setForeground(Color.blue);for(int i=0;i<42;i++){showDay[i]=new JTextField();showDay[i].addMouseListener(this);showDay[i].setEditable(false);leftCenter.add(showDay[i]);}日历=Calendar.getInstance();Box box=Box.createHorizontalBox();box.add(负责改变年);box.add(负责改变月);leftNorth.add(box);leftPanel.setLayout(new BorderLayout());leftPanel.add(leftNorth,BorderLayout.NORTH);leftPanel.add(leftCenter,BorderLayout.CENTER);leftPanel.add(new Label("请在年份输入框输入所查年份(负数表示公元前),并回车确定"), ~ 6 / 25 ~BorderLayout.SOUTH) ;leftPanel.validate();Container con=getContentPane();JSplitPane split=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftPanel,rightPanel);con.add(split,BorderLayout.CENTER);con.validate();hashtable=new Hashtable();file=new File("日历记事本.txt");if(!file.exists()){try{FileOutputStream out=new FileOutputStream(file);ObjectOutputStream objectOut=new ObjectOutputStream(out);objectOut.writeObject(hashtable);objectOut.close();out.close();}catch(IOException e){}}notepad=new NotePad(this);rightPanel.add(notepad);设置日历牌(year,month);~ 7 / 25 ~addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){System.exit(0);}});setVisible(true);setBounds(100,50,524,285);validate();}public void 设置日历牌(int year,int month){日历.set(year,month-1,1);星期几=日历.get(Calendar.DAY_OF_WEEK)-1;if(month==1||month==2||month==3||month==5||month==7||month==8||month==10||month==12) {排列号码(星期几,31);}else if(month==4||month==6||month==9||month==11){排列号码(星期几,30);}else if(month==2){if((year%4==0&&year%100!=0)||(year%400==0)){排列号码(星期几,29);}~ 8 / 25 ~else{排列号码(星期几,28);}}public void 排列号码(int 星期几,int 月天数){for(int i=星期几,n=1;i<星期几+月天数;i++){showDay[i].setText(""+n);if(n==day){showDay[i].setForeground(Color.green);showDay[i].setFont(new Font("TimesRoman",Font.BOLD,20));}else{showDay[i].setFont(new Font("TimesRoman",Font.BOLD,12));showDay[i].setForeground(Color.black);}if(i%7==6){showDay[i].setForeground(Color.blue);}if(i%7==0){showDay[i].setForeground(Color.red);~ 9 / 25 ~}n++;}for(int i=0;i<星期几;i++){showDay[i].setText("");}for(int i=星期几+月天数;i<42;i++){showDay[i].setText("");}}public int getYear(){return year;}public void setYear(int y){year=y;notepad.setYear(year);public int getMonth(){return month;}public void setMonth(int m){month=m;notepad.setMonth(month);}public int getDay(){return day;}public void setDay(int d){day=d;notepad.setDay(day);}public Hashtable getHashtable(){return hashtable;}public File getFile(){return file;}public void mousePressed(MouseEvent e){JTextField source=(JTextField)e.getSource(); try{day=Integer.parseInt(source.getText());notepad.setDay(day);notepad.设置信息条(year,month,day);notepad.设置文本区(null);notepad.获取日志内容(year,month,day);}catch(Exception ee){}}public void mouseClicked(MouseEvent e){}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public static void main(String args[]){Calendar calendar=Calendar.getInstance();int y=calendar.get(Calendar.YEAR);int m=calendar.get(Calendar.MONTH)+1;int d=calendar.get(Calendar.DAY_OF_MONTH);new CalendarPad(y,m,d);}}2、)Month类import javax.swing.*;import java.awt.*;import java.awt.event.*;~ 11 / 25 ~public class Month extends Box implements ActionListener{int month;JTextField showMonth=null;JButton 下月,上月;CalendarPad 日历;public Month(CalendarPad 日历){super(BoxLayout.X_AXIS);this.日历=日历;showMonth=new JTextField(2);month=日历.getMonth();showMonth.setEditable(false);showMonth.setForeground(Color.blue);showMonth.setFont(new Font("TimesRomn",Font.BOLD,16));下月=new JButton("下月");上月=new JButton("上月");add(上月);add(showMonth);add(下月);上月.addActionListener(this);下月.addActionListener(this);showMonth.setText(""+month);}public void setMonth(int month){if(month<=12&&month>=1){this.month=month;}else{this.month=1;}showMonth.setText(""+month);~ 12 / 25 ~}public int getMonth(){return month;}public void actionPerformed(ActionEvent e){if(e.getSource()==上月){if(month>=2){month=month-1;日历.setMonth(month);日历.设置日历牌(日历.getYear(),month);}else if(month==1){month=12;日历.setMonth(month);日历.设置日历牌(日历.getYear(),month);}showMonth.setText(""+month);}else if(e.getSource()==下月){if(month<12){month=month+1;日历.setMonth(month);日历.设置日历牌(日历.getYear(),month);}else if(month==12){month=1;日历.setMonth(month);日历.设置日历牌(日历.getYear(),month);}showMonth.setText(""+month);}~ 13 / 25 ~}}3、)NotePad类import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;import javax.swing.event.*;import java.io.*;public class NotePad extends JPanel implements ActionListener{JTextArea text;JButton 保存日志,删除日志;Hashtable table;JLabel 信息条;int year,month,day;File file;CalendarPad calendar;public NotePad(CalendarPad calendar){this.calendar=calendar;year=calendar.getYear();month=calendar.getMonth();day=calendar.getDay();;table=calendar.getHashtable();file=calendar.getFile();信息条=new JLabel(""+year+"年"+month+"月"+day+"日",JLabel.CENTER);信息条.setFont(new Font("TimesRoman",Font.BOLD,16));信息条.setForeground(Color.blue);text=new JTextArea(10,10);~ 14 / 25 ~保存日志=new JButton("保存日志") ;删除日志=new JButton("删除日志") ;保存日志.addActionListener(this);删除日志.addActionListener(this);setLayout(new BorderLayout());JPanel pSouth=new JPanel();add(信息条,BorderLayout.NORTH);pSouth.add(保存日志);pSouth.add(删除日志);add(pSouth,BorderLayout.SOUTH);add(new JScrollPane(text),BorderLayout.CENTER); }public void actionPerformed(ActionEvent e){if(e.getSource()==保存日志){保存日志(year,month,day);}else if(e.getSource()==删除日志){删除日志(year,month,day);}}public void setYear(int year){this.year=year;}public int getYear(){return year;}public void setMonth(int month){this.month=month;}public int getMonth(){return month;}public void setDay(int day){this.day=day;}public int getDay(){return day;}public void 设置信息条(int year,int month,int day){信息条.setText(""+year+"年"+month+"月"+day+"日");}public void 设置文本区(String s){text.setText(s);}public void 获取日志内容(int year,int month,int day){String key=""+year+""+month+""+day;try{FileInputStream inOne=new FileInputStream(file);ObjectInputStream inTwo=new ObjectInputStream(inOne);table=(Hashtable)inTwo.readObject();inOne.close();inTwo.close();}catch(Exception ee){}if(table.containsKey(key)){String m=""+year+"年"+month+"月"+day+"这一天有日志记载,想看吗?";int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,~ 16 / 25 ~JOptionPane.QUESTION_MESSAGE);if(ok==JOptionPane.YES_OPTION){text.setText((String)table.get(key));}else{text.setText("");}}else{text.setText("无记录");}}public void 保存日志(int year,int month,int day){String 日志内容=text.getText();String key=""+year+""+month+""+day;String m=""+year+"年"+month+"月"+day+"保存日志吗?";int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);if(ok==JOptionPane.YES_OPTION){try~ 17 / 25 ~{FileInputStream inOne=new FileInputStream(file);ObjectInputStream inTwo=new ObjectInputStream(inOne);table=(Hashtable)inTwo.readObject();inOne.close();inTwo.close();table.put(key,日志内容);FileOutputStream out=new FileOutputStream(file);ObjectOutputStream objectOut=new ObjectOutputStream(out);objectOut.writeObject(table);objectOut.close();out.close();}catch(Exception ee){}}}public void 删除日志(int year,int month,int day){String key=""+year+""+month+""+day;if(table.containsKey(key)){String m="删除"+year+"年"+month+"月"+day+"日的日志吗?";~ 18 / 25 ~int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);if(ok==JOptionPane.YES_OPTION){try{FileInputStream inOne=new FileInputStream(file);ObjectInputStream inTwo=new ObjectInputStream(inOne);table=(Hashtable)inTwo.readObject();inOne.close();inTwo.close();table.remove(key);FileOutputStream out=new FileOutputStream(file);ObjectOutputStream objectOut=new ObjectOutputStream(out);objectOut.writeObject(table);objectOut.close();~ 19 / 25 ~out.close();text.setText(null);}catch(Exception ee){}}}else{String m=""+year+"年"+month+"月"+day+"无日志记录";JOptionPane.showMessageDialog(this,m,"提示",JOptionPane.WARNING_MESSAGE);}}}4、)Year 类import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Year extends Box implements ActionListener{int year;JTextField showYear=null;JButton 明年,去年;CalendarPad 日历;public Year(CalendarPad 日历){super(BoxLayout.X_AXIS);showYear=new JTextField(4);showYear.setForeground(Color.blue);showYear.setFont(new Font("TimesRomn",Font.BOLD,14));this.日历=日历;year=日历.getYear();明年=new JButton("下年");去年=new JButton("上年");add(去年);add(showYear);add(明年);showYear.addActionListener(this);去年.addActionListener(this);明年.addActionListener(this);}public void setYear(int year){this.year=year;showYear.setText(""+year);}public int getYear(){return year;}public void actionPerformed(ActionEvent e){if(e.getSource()==去年){year=year-1;showYear.setText(""+year);日历.setYear(year);日历.设置日历牌(year,日历.getMonth());}else if(e.getSource()==明年){year=year+1;showYear.setText(""+year);日历.setYear(year);日历.设置日历牌(year,日历.getMonth());}else if(e.getSource()==showYear){try{year=Integer.parseInt(showYear.getText()); ~ 21 / 25 ~showYear.setText(""+year);日历.setYear(year);日历.设置日历牌(year,日历.getMonth());}catch(NumberFormatException ee){showYear.setText(""+year);日历.setYear(year);日历.设置日历牌(year,日历.getMonth());}}}}。

JAVA--简单记事本源代码

JAVA--简单记事本源代码

JAVA--简单记事本源代码import javax.swing.JFrame;import javax.swing.JTextArea;import java.awt.*;import java.awt.event.*;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import javax.swing.*;import javax.swing.plaf.FileChooserUI;public class notepad extends JFrame implements ActionListener{//定义所需要的组件JTextArea jta=null;JMenuBar jmb=null;JMenu jm=null;JMenuItem jmi1=null;JMenuItem jmi2=null;public static void main(String[]args){new notepad();}public notepad(){//把组件添加到窗体上jta=new JTextArea();jmb=new JMenuBar();this.add(jta);this.setJMenuBar(jmb);//设置窗体属性this.setTitle("简易记事本");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(400, 300);this.setVisible(true);//把菜单添加进菜单条jm=new JMenu("⽂件");jm.setMnemonic('f');jmb.add(jm);//把⼦菜单加⼊⾄菜单jmi1=new JMenuItem("打开");jmi2=new JMenuItem("保存");jmi1.setActionCommand("open");jmi2.setActionCommand("save");jm.add(jmi1);jm.add(jmi2);//为两个字菜单注册事件监听jmi1.addActionListener(this);jmi2.addActionListener(this);}public void actionPerformed(ActionEvent e){//对点击了打开进⾏处理if(e.getActionCommand().equals("open")){//创建⼀个⽂件选择组件JFileChooser jfc1=new JFileChooser();//设置⽂件选择器的名字jfc1.setDialogTitle("请选择⽂件....");//设置⽂件选择组件的类型(打开类型)jfc1.showOpenDialog(null);//显⽰该组件jfc1.setVisible(true);//获取选择⽂件的绝对路径String s;s=jfc1.getSelectedFile().getAbsolutePath();//将该⽂件显⽰到记事本上BufferedReader br=null;FileReader fr=null;try{//创建⼀个带缓冲的⽂件读取对象fr=new FileReader(s);br=new BufferedReader(fr);String text="";String m=null;//循环读取⽂件while((m=br.readLine())!=null){text+=m+"\r\n";}//将读取的结果打印到记事本上⾯this.jta.setText(text);}catch(Exception e1){e1.printStackTrace();}finally{//关掉打开的⽂件try{br.close();fr.close();}catch(Exception e2){e2.printStackTrace();}}}else if(e.getActionCommand().equals("save")){//创建⼀个⽂件选择组件JFileChooser jfc=new JFileChooser();//设置⽂件选择的名称jfc.setDialogTitle("另存为");//设置⽂件选择组件的类型(保存类型)jfc.showSaveDialog(null);//显⽰该组件jfc.setVisible(true);//获取选择⽂件的绝对路径String filename;filename=jfc.getSelectedFile().getAbsolutePath(); //将记事本内的⽂本保存⾄该路径BufferedWriter bw=null;FileWriter fw=null;try{//创建⽂件输出⽂件fw=new FileWriter(filename);bw=new BufferedWriter(fw);//获取⽂本String outtext="";outtext=this.jta.getText();//输出⽂本fw.write(outtext);}catch(Exception e2){e2.printStackTrace();}finally{//关闭打开的输出⽂件try{bw.close();fw.close();}catch(Exception e3){e3.printStackTrace();}}}}}。

记事本源代码

记事本源代码

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.setV isible(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.SA VE);fDlg.setV isible(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 对象。

记事本源代码

记事本源代码

//记事本源代码package jishiben;import java.awt.*;import javax.swing.*;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;import java.awt.event.*;import java.io.*;import java.util.Calendar;import jishiben.FWindow.StyleDialog;public class FristWindow {public static void main(String[] args) {// TODO Auto-generated method stubnew FWindow("记事本");}}class FWindow extends JFrame implements ActionListener,WindowListener,ItemListener { public static Frame frame;JMenuBar menuBar;JPopupMenu menu;//用户在菜单栏上选择项时显示的菜单JMenu menu1,menu2,menu3,menu4,menu5;JMenuItemitem1,item2,item3,item4,item5,item21,item22,item23,item24,item25,item26,item27,item31,item3 2,item41,item51,item52;JMenuItem itemCopy,itemCut,itemPaste;JTextArea text;//显示纯文本的多行区域JScrollPane scrollPane;JComboBox listFont,listFSize;int save_status=0,status=0,huanhang_count=0;FWindow(String s){//窗口的监听addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent event)//关闭窗口的事件{if(save_status==0){//JOptionPane弹出要求用户提供值或向其发出通知的标准对话框//showConfirmDialog询问一个确认问题int check=JOptionPane.showConfirmDialog(null,"文件的文字已经改变,想保存文件吗?","警告",JOptionPane.YES_NO_CANCEL_OPTION);if(check==0){saveFile(status);}if (check==1) {System.exit(0);}if (check==2) {dispose();}}}});//位置setTitle("记事本");setSize(700,400);setLocation(120, 120);menuBar=new JMenuBar();setJMenuBar(menuBar);text=new JTextArea(30,40);text.setLineWrap(true);//滚动条scrollPane=new JScrollPane(text);//文本框的滚动条add(scrollPane);scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWA YS);scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);menu=new JPopupMenu();menu1=new JMenu("文件");menu1.addActionListener(this);//监听文件菜单menu2=new JMenu("编辑");menu3=new JMenu("格式");menu4=new JMenu("查看");menu5=new JMenu("帮助");menuBar.add(menu1);menuBar.add(menu2);menuBar.add(menu3);menuBar.add(menu4);menuBar.add(menu5);//文件菜单下菜单项的创建并监听item1=new JMenuItem("新建");item1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item1) {text.setText("");this.setTitle("无标题- 记事本");}}private void setTitle(String string){// TODO Auto-generated method stub}});//文件菜单下菜单项的打开并监听item2=new JMenuItem("打开");item2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item2) {File fl;JFileChooser jfc1=new JFileChooser("F:/");//选择打开文件的位置int num1=jfc1.showOpenDialog(null);if (num1==JFileChooser.APPROVE_OPTION) {try {fl=jfc1.getSelectedFile();this.setTitle(fl.getName());FileReader fr=new FileReader(fl);BufferedReader br=new BufferedReader(fr);String str;while((str=br.readLine())!=null){text.setText(str);}fr.close();br.close();} catch (FileNotFoundException e1) {// TODO: handle exceptione1.printStackTrace();}catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}}}}//p12方法private void setTitle(String name){}});//文件菜单下菜单项的保存并监听item3=new JMenuItem("保存");item3.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item3) {File f2=null;JFileChooser jfc2=new JFileChooser();int num2=jfc2.showSaveDialog(null);if(num2==JFileChooser.APPROVE_OPTION){f2=jfc2.getSelectedFile();this.setTitle(f2.getName());try {FileWriter fw=new FileWriter(f2);BufferedWriter bw=new BufferedWriter(fw);bw.write(text.getText());bw.close();fw.close();} catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}}}}private void setTitle(String name){}});//另存为、退出//===================================另存为有问题===============================================//item4=new JMenuItem("另存为...");item4.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub/*if (e.getActionCommand().equals(" 另存为")) {Frame f=new Frame(" 保存");FileDialog fd=new FileDialog(f," 文件另存为",FileDialog.SA VE);fd.setVisible(true);try {String savepath=fd.getDirectory();String savename=fd.getFile();if (savename!=null) {PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(savepath+savename)));pw.write(text.getText(),0,text.getText().length());pw.flush();}} catch (Exception easve) {// TODO: handle exception}}*/if (e.getSource()==item4) {File f3=null;JFileChooser jfc3=new JFileChooser();int num3=jfc3.showSaveDialog(null);if(num3==JFileChooser.APPROVE_OPTION){f3=jfc3.getSelectedFile();this.setTitle(f3.getName());try {FileWriter fw=new FileWriter(f3);BufferedWriter bw=new BufferedWriter(fw);bw.write(text.getText());bw.close();fw.close();} catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}}}}private void setTitle(String name){}});item5=new JMenuItem("退出");//文件菜单下菜单项的退出并监听item5.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item5) {int a=JOptionPane.showConfirmDialog(null,"文件已被改变,是否保存?","提示",JOptionPane.YES_NO_CANCEL_OPTION);if (a==1) {this.dispose();}else if(a==0){File f2=null;JFileChooser jfc2=new JFileChooser();int num2=jfc2.showSaveDialog(null);if (num2==JFileChooser.APPROVE_OPTION) {f2=jfc2.getSelectedFile();this.setTitle(f2.getName());try {FileWriter fw=new FileWriter(f2);BufferedWriter bw=new BufferedWriter(fw);bw.write(text.getText());bw.close();fw.close();} catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}this.dispose();}}}}private void setTitle(String name){}private void dispose(){}});//KeyStroke 仅能对应于按下或释放某个特定的键//返回KeyStroke 的实例,指定该键在按下或释放时是否视为已激活//CTRL_MASK Ctrl 键修饰符常量。

Java 记事本设计完整代码

Java 记事本设计完整代码
String text = content.getText();
String str = findtext.getText();
int end = text.length();
int len = str.length();
int start = content.getSelectionEnd();
if (start == end) {
boolean status=false;
mynotepad() {
initTextContent();
initMenu();
}
void initTextContent() {
JScrollPane scroll = new JScrollPane(content);
getContentPane().add(scroll);
public void actionPerformed(ActionEvent e) {
final JDialog dialog = new JDialog(about, "查找字符串...",
true);
dialog.setBounds(560, 250, 310, 130);
JLabel find = new JLabel("请输入字符串:");
// TODO Auto-generated method stub
JTextArea editArea = (JTextArea)e.getSource();
int linenum = 1;
int columnnum = 1;
try {
int caretpos = editArea.getCaretPosition();

Java完整简单记事本源代码

Java完整简单记事本源代码

版权所有请勿抄袭AboutDialog.javapackage notepad;import java.awt.Color;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;public class AboutDialog implements ActionListener{public JDialog Dialog;public JButton OK,Icon;public JLabel Name,Version,Author,Java;public JPanel Panel;AboutDialog(JFrame notepad, int x, int y) {Dialog=new JDialog(notepad,"About Notepad...",true);OK=new JButton("OK");Icon=new JButton(new ImageIcon("Notepad.jpg"));Name=new JLabel("Notepad");Version=new JLabel("Version 1.0");Java=new JLabel("JRE Version 6.0");Author=new JLabel("Copyright (c) 2011 Sky. No rights reserved.");Panel=new JPanel();Color c=new Color(0,95,191);Name.setForeground(c);Version.setForeground(c);Java.setForeground(c);Panel.setBackground(Color.WHITE);OK.setFocusable(false);Dialog.setSize(280, 180);Dialog.setLocation(x, y);Dialog.setResizable(false);Dialog.setLayout(null);Panel.setLayout(null);OK.addActionListener(this);Icon.setFocusable(false);Icon.setBorderPainted(false);Author.setFont(new Font(null,Font.PLAIN,11));Panel.add(Icon);Panel.add(Name);Panel.add(Version);Panel.add(Author);Panel.add(Java);Dialog.add(Panel);Dialog.add(OK);Panel.setBounds(0, 0, 280, 100);OK.setBounds(180, 114, 72, 26);Name.setBounds(80, 10, 160, 20);Version.setBounds(80, 27, 160, 20);Author.setBounds(15, 70, 250, 20);Java.setBounds(80, 44, 160, 20);Icon.setBounds(16, 14, 48, 48);}public void actionPerformed(ActionEvent e) { Dialog.setVisible(false);}}ColorDialog.javapackage notepad;import java.awt.Color;import ponent;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class ColorDialog implements ActionListener, WindowListener{ public JDialog Dialog;public JLabel NFL,NBL,SFL,SBL;public JTextArea Normal,Selected;public JButton NFB,NBB,SFB,SBB,OK,Cancel,Reset;public Color NFC,NBC,SFC,SBC;public ColorChooser Chooser;public ColorDialog(JFrame notepad, int x, int y){NFC=new Color(0,0,0);NBC=new Color(249,249,251);SFC=new Color(0,0,0);SBC=new Color(191,207,223);Dialog=new JDialog(notepad,"Color...",true);NFL=new JLabel("Normal Foreground:");NBL=new JLabel("Normal Background:");SFL=new JLabel("Selected Foreground:");SBL=new JLabel("Selected Background:");Normal=new JTextArea("\n Normal 正常");Selected=new JTextArea("\n Selected 选中 ");NFB=new JButton("");NBB=new JButton("");SFB=new JButton("");SBB=new JButton("");OK=new JButton("OK");Cancel=new JButton("Cancel");Reset=new JButton("Reset");Chooser=new ColorChooser(Dialog, x+65, y-15);Normal.setEditable(false);Normal.setFocusable(false);Normal.setFont(new Font("新宋体", 0, 16));Normal.setForeground(NFC);Normal.setBackground(NBC);Selected.setEditable(false);Selected.setFocusable(false);Selected.setFont(Normal.getFont());Selected.setForeground(SFC);Selected.setBackground(SBC);NFB.setBackground(NFC);NBB.setBackground(NBC);SFB.setBackground(SFC);SBB.setBackground(SBC);Dialog.setLayout(null);Dialog.setLocation(x, y);Dialog.setSize(410, 220);Dialog.setResizable(false);Reset.setFocusable(false);OK.setFocusable(false);Cancel.setFocusable(false);Dialog.add(Normal);Dialog.add(Selected);Dialog.add(NFL);Dialog.add(NBL);Dialog.add(SFL);Dialog.add(SBL);Dialog.add(SBB);Dialog.add(SFB);Dialog.add(NBB);Dialog.add(NFB);Dialog.add(OK);Dialog.add(Cancel);Dialog.add(Reset);SBB.setBounds(144, 100, 60, 22);SFB.setBounds(144, 70, 60, 22);NBB.setBounds(144, 40, 60, 22);NFB.setBounds(144, 10, 60, 22);NFL.setBounds(10, 10, 130, 22);NBL.setBounds(10, 40, 130, 22);SFL.setBounds(10, 70, 130, 22);SBL.setBounds(10, 100, 130, 22);Normal.setBounds(220, 10, 174, 56);Selected.setBounds(220, 66, 174, 56);Reset.setBounds(10, 160, 74, 24);OK.setBounds(236, 160, 74, 24);Cancel.setBounds(320, 160, 74, 24);Dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);Dialog.addWindowListener(this);NFB.addActionListener(this);NBB.addActionListener(this);SFB.addActionListener(this);SBB.addActionListener(this);Reset.addActionListener(this);OK.addActionListener(this);Cancel.addActionListener(this);}public void setTextAreaColor(){Normal.setForeground(NFB.getBackground());Normal.setBackground(NBB.getBackground());Selected.setForeground(SFB.getBackground());Selected.setBackground(SBB.getBackground());}public void cancel(){Normal.setForeground(NFC);Normal.setBackground(NBC);Selected.setForeground(SFC);Selected.setBackground(SBC);NFB.setBackground(NFC);NBB.setBackground(NBC);SFB.setBackground(SFC);SBB.setBackground(SBC);Dialog.setVisible(false);}public void actionPerformed(ActionEvent e) {Object obj=e.getSource();if(obj==Reset){NFB.setBackground(new Color(0,0,0));NBB.setBackground(new Color(249,249,251));SFB.setBackground(new Color(0,0,0));SBB.setBackground(new Color(191,207,223));setTextAreaColor();}else if(obj==OK){NFC=NFB.getBackground();NBC=NBB.getBackground();SFC=SFB.getBackground();SBC=SBB.getBackground();Dialog.setVisible(false);}else if(obj==Cancel)cancel();else{Chooser.init(((Component) obj).getBackground());Chooser.Dialog.setVisible(true);((Component) obj).setBackground(Chooser.New.getBackground());setTextAreaColor();}}public void windowClosing(WindowEvent e) {cancel();}public void windowActivated(WindowEvent arg0) {}public void windowClosed(WindowEvent arg0) {}public void windowDeactivated(WindowEvent arg0) {}public void windowDeiconified(WindowEvent arg0) {}public void windowIconified(WindowEvent arg0) {}public void windowOpened(WindowEvent arg0) {}}class ColorChooser implements ActionListener,WindowListener,KeyListener{ JDialog Dialog;JButton Choice[][],Old,New,OK,Cancel;JPanel Panel;JTextField R,G,B;JLabel OldLabel,NewLabel,RL,GL,BL;ColorChooser(JDialog color,int x, int y){Dialog=new JDialog(color,true);Choice=new JButton[8][8];Panel=new JPanel();Old=new JButton("");New=new JButton("");OldLabel=new JLabel("Old:");NewLabel=new JLabel("New:");RL=new JLabel("R:");GL=new JLabel("G:");BL=new JLabel("B:");R=new JTextField("");G=new JTextField("");B=new JTextField("");OK=new JButton("OK");Cancel=new JButton("Cancel");Panel.setLayout(new GridLayout(8,8,0,0));int i=0,j=0;Color c;Choice[0][7]=new JButton("");Choice[0][7].setBackground(new Color(255,255,255));Choice[1][7]=new JButton("");Choice[1][7].setBackground(new Color(255,223,191));Choice[2][7]=new JButton("");Choice[2][7].setBackground(new Color(255,207,207));Choice[3][7]=new JButton("");Choice[3][7].setBackground(new Color(223,191,255));Choice[4][7]=new JButton("");Choice[4][7].setBackground(new Color(207,207,255));Choice[5][7]=new JButton("");Choice[5][7].setBackground(new Color(191,223,255));Choice[6][7]=new JButton("");Choice[6][7].setBackground(new Color(207,255,207));Choice[7][7]=new JButton("");Choice[7][7].setBackground(new Color(223,255,191));for(i=0;i<8;i++){c=Choice[i][7].getBackground();for(j=0;j<8;j++){if(j!=7){Choice[i][j]=new JButton("");Choice[i][j].setBackground(newColor(c.getRed()*(j+1)/8,c.getGreen()*(j+1)/8,c.getBlue()*(j+1)/8));}Choice[i][j].setFocusable(false);Choice[i][j].addActionListener(this);Panel.add(Choice[i][j]);}}Dialog.setSize(280,250);Dialog.setLayout(null);Dialog.setLocation(x, y);Dialog.setResizable(false);Dialog.add(Panel);Panel.setBounds(10, 10, 160, 160);Dialog.add(Old);Dialog.add(OldLabel);Old.setEnabled(false);Old.setBorderPainted(false);Old.setBounds(214, 10, 44, 22);OldLabel.setBounds(180, 10, 44, 22);Dialog.add(New);Dialog.add(NewLabel);New.setEnabled(false);New.setBorderPainted(false);New.setBounds(214, 32, 44, 22);NewLabel.setBounds(180, 32, 44, 22);Dialog.add(R);Dialog.add(G);Dialog.add(B);R.setBounds(214, 97, 44, 22);G.setBounds(214, 123, 44, 22);B.setBounds(214, 149, 44, 22);Dialog.add(RL);Dialog.add(GL);Dialog.add(BL);RL.setBounds(196, 97, 16, 22);GL.setBounds(196, 123, 16, 22);BL.setBounds(196, 149, 16, 22);Dialog.add(OK);Dialog.add(Cancel);OK.setFocusable(false);Cancel.setFocusable(false);OK.setBounds(106, 190, 74, 24);Cancel.setBounds(190, 190, 74, 24);OK.addActionListener(this);Cancel.addActionListener(this);G.addKeyListener(this);R.addKeyListener(this);B.addKeyListener(this);}public void setText(Color c){R.setText(String.valueOf(c.getRed()));G.setText(String.valueOf(c.getGreen()));B.setText(String.valueOf(c.getBlue()));}public void init(Color c){New.setBackground(c);Old.setBackground(c);setText(c);}public void actionPerformed(ActionEvent e) { Object obj=e.getSource();if(obj==OK) Dialog.setVisible(false);else if(obj==Cancel){New.setBackground(Old.getBackground());Dialog.setVisible(false);}else{New.setBackground(((Component) obj).getBackground());setText(New.getBackground());}}public void windowClosing(WindowEvent e) {New.setBackground(Old.getBackground());Dialog.setVisible(false);}public void keyReleased(KeyEvent e) {try{int r,g,b;if(R.getText().length()==0) r=0;else r=Integer.valueOf(R.getText());if(G.getText().length()==0) g=0;else g=Integer.valueOf(G.getText());if(B.getText().length()==0) b=0;else b=Integer.valueOf(B.getText());New.setBackground(new Color(r,g,b));}catch(NumberFormatException nfe){setText(New.getBackground());}catch(IllegalArgumentException iae){setText(New.getBackground());} }public void keyPressed(KeyEvent e) {}public void keyTyped(KeyEvent e) {}public void windowActivated(WindowEvent arg0) {}public void windowClosed(WindowEvent arg0) {}public void windowDeactivated(WindowEvent arg0) {}public void windowDeiconified(WindowEvent arg0) {}public void windowIconified(WindowEvent arg0) {}public void windowOpened(WindowEvent arg0) {}}EnsureDialog.javapackage notepad;import java.awt.BorderLayout;import java.awt.Color;import java.awt.FlowLayout;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;public class EnsureDialog implements WindowListener, ActionListener{ public int YES,NO,CANCEL,Status;public JDialog Ensure;public JButton Yes,No,Cancel;public JLabel Question;public JPanel ButtonPanel,TextPanel;EnsureDialog(JFrame notepad, int x, int y) {YES=0;NO=1;CANCEL=2;Status=CANCEL;Ensure=new JDialog(notepad,true);/** 这里的模式标志true的作用是使对话框处于notepad的上端,并且当对话框显示时进程处于停滞状态, * 直到对话框不再显示为止。

Java记事本源代码

Java记事本源代码

import java.awt.*;import java.awt.datatransfer.DataFlavor;import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants;import java.awt.dnd.DropTarget;import java.awt.dnd.DropTargetAdapter;import java.awt.dnd.DropTargetDropEvent; import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.AdjustmentEvent;import java.awt.event.AdjustmentListener; import java.awt.event.InputEvent;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import java.awt.print.PageFormat;import java.awt.print.Printable;import java.awt.print.PrinterException;import java.awt.print.PrinterJob;import java.io.*;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.Stack;import java.util.List;import javax.swing.*;import javax.swing.event.CaretEvent;import javax.swing.event.CaretListener;import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document;import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel;//文件->新建N CTRL+Nclass 新建implements ActionListener {private JTextArea editText;private boolean choose;public JFrame frame;public static String path1;//在打开的事件中path1="";public String str;新建() {this.editText = JLinePrint.editText;path1="";NewMenu();}//新建public void NewMenu(){//建立询问框,设置大小位置,设为自己布局frame=new JFrame("记事本");frame.setBounds(424, 269, 355, 181);frame.setLayout(null);//建立两个标签JLabel label1=new JLabel("文件的内容已经改变");label1.setFont(new Font("新宋体",Font.PLAIN,14));JLabel label2=new JLabel("想保存文件吗?:)");label2.setFont(new Font("新宋体",Font.PLAIN,14));label1.setBounds(113,23,180, 23);label2.setBounds(113,46,180,23);frame.add(label1);frame.add(label2);//建立"是"按钮JButton button_Yes=new JButton("是(Y)");button_Yes.setMnemonic(KeyEvent.VK_Y);//按ALT+Y选择//给"是"按钮加上事件监听button_Yes.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e1){保存.path="";//保存类的路径清空保存.FirstSave=false;//保存类恢复未保存状态//与另存为相同choose=false;//条件未满足,不保存//弹框设定路径FileDialog filedialog=new FileDialog(frame,"另存为",FileDialog.SAVE);filedialog.setVisible(true);path1=filedialog.getDirectory()+filedialog.getFile()+".txt";//如果为选择路径(文件名为null或nullnull),则直接返回if(path1.equals("nullnull.txt")||path1.equals(filedialog.getDirectory()+"null.txt")){return;}//iffinal File file=new File(path1);choose=true;//满足条件,设为能保存状态if( file.exists()){//如果文件重名choose=false; //有条件不满足,重设为不能保存状态final JFrame f=new JFrame("另存为");f.setBounds(435,276,path1.length()*7+200,125);f.setVisible(true);f.setLayout(null);JLabel label=new JLabel(path1+"已存在。

java记事本源代码

java记事本源代码
m12.setAccelerator(keysave);
JMenuItem m13=new JMenuItem("另保存为 ");
m13.addActionListener(this);
JMenuItem m14=new JMenuItem("退出 ");
m14.addActionListener(this);
{
myfr fr=new myfr("JAVA记事本");
fr.setSize(560,395);
}
}
///////////////////////////myfr主窗体类//////////////////////////////////////
class myfr extends JFrame implements ActionListener
JTextArea txt1; //主输入文本区
File newfiles;
JPopupMenu popm; //弹出菜单声明
//JMenu m1,m2,m3,m4,m5,m6; //各菜单项
JMenu m1, m2, m3;
JMenuItem m26,m271,m34,p_copy,p_cut,p_paste,p_del;
replb.addActionListener(this);
mainpane=(JPanel)this.getContentPane();
mainpane.setLayout(new BorderLayout());
txt1=new JTextArea("",13,61);
m21.setAccelerator(keycopy);

Java记事本源代码(完整)

Java记事本源代码(完整)

/*** 作品:记事本* **** 功能:简单的文字编辑*/import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;class NotePad extends JFrame{private JMenuBar menuBar;private JMenu fielMenu,editMenu,formMenu,aboutMenu;private JMenuItemnewMenuItem,openMenuItem,saveMenuItem,exitMenuItem;private JMenuItemcutMenuItem,copyMenuItem,pasteMenuItem,foundItem,replaceItem,s electAll;private JMenuItem font,about;private JTextArea textArea;private JFrame foundFrame,replaceFrame;private JCheckBoxMenuItem wrapline;private JTextField textField1=new JTextField(15);private JTextField textField2=new JTextField(15);private utton startButton,replaceButton,reallButton;int start=0;String value;File file=null;JFileChooser fileChooser=new JFileChooser();boolean wrap=false;public NotePad(){//创建文本域textArea=new JTextArea();add(new JScrollPane(textArea),BorderLayout.CENTER);//创建文件菜单与文件菜单项fielMenu=new JMenu("文件");fielMenu.setFont(new Font("微软雅黑",0,15));newMenuItem=new JMenuItem("新建",newImageIcon("icons\\new24.gif"));newMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13)); newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ N,InputEvent.CTRL_MASK));newMenuItem.addActionListener(listener);openMenuItem=new JMenuItem("打开",newImageIcon("icons\\open24.gif"));openMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13)); openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _O,InputEvent.CTRL_MASK));openMenuItem.addActionListener(listener);saveMenuItem=new JMenuItem("保存",newImageIcon("icons\\save.gif"));saveMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13)); saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _S,InputEvent.CTRL_MASK));saveMenuItem.addActionListener(listener);exitMenuItem=new JMenuItem("退出",newImageIcon("icons\\exit24.gif"));exitMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13)); exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _E,InputEvent.CTRL_MASK));exitMenuItem.addActionListener(listener);//创建编辑菜单与菜单项editMenu=new JMenu("编辑");editMenu.setFont(new Font("微软雅黑",0,15));cutMenuItem=new JMenuItem("剪切",newImageIcon("icons\\cut24.gif"));cutMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13)); cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ X,InputEvent.CTRL_MASK));cutMenuItem.addActionListener(listener);copyMenuItem=new JMenuItem("复制",newImageIcon("icons\\copy24.gif"));copyMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13)); copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _C,InputEvent.CTRL_MASK));copyMenuItem.addActionListener(listener);pasteMenuItem=new JMenuItem("粘贴",newImageIcon("icons\\paste24.gif"));pasteMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13)); pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.V K_V,InputEvent.CTRL_MASK));pasteMenuItem.addActionListener(listener);foundItem=new JMenuItem("查找");foundItem.setFont(new Font("微软雅黑",Font.BOLD,13)); foundItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK));foundItem.addActionListener(listener);replaceItem=new JMenuItem("替换");replaceItem.setFont(new Font("微软雅黑",Font.BOLD,13)); replaceItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ R,InputEvent.CTRL_MASK));replaceItem.addActionListener(listener);selectAll=new JMenuItem("全选");selectAll.setFont(new Font("微软雅黑",Font.BOLD,13)); selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));selectAll.addActionListener(listener);//创建格式菜单与菜单项formMenu=new JMenu("格式");formMenu.setFont(new Font("微软雅黑",0,15));wrapline=new JCheckBoxMenuItem("自动换行");wrapline.setFont(new Font("微软雅黑",Font.BOLD,13)); wrapline.addActionListener(listener);wrapline.addChangeListener(new ChangeListener() {publicvoid stateChanged(ChangeEvent e) {if(wrapline.isSelected()){textArea.setLineWrap(true);}elsetextArea.setLineWrap(false);}});font=new JMenuItem("字体");font.setFont(new Font("微软雅黑",Font.BOLD,13));font.addActionListener(listener);//创建关于菜单aboutMenu=new JMenu("关于");aboutMenu.setFont(new Font("微软雅黑",0,15)); about=new JMenuItem("记事本……");about.setFont(new Font("微软雅黑",Font.BOLD,13)); about.addActionListener(listener);//添加文件菜单项fielMenu.add(newMenuItem);fielMenu.add(openMenuItem);fielMenu.add(saveMenuItem);fielMenu.addSeparator();fielMenu.add(exitMenuItem);//添加编辑菜单项editMenu.add(cutMenuItem);editMenu.add(copyMenuItem);editMenu.add(pasteMenuItem);editMenu.add(foundItem);editMenu.add(replaceItem);editMenu.addSeparator();editMenu.add(selectAll);//添加格式菜单项formMenu.add(wrapline);formMenu.add(font);//添加关于菜单项aboutMenu.add(about);//添加菜单menuBar=new JMenuBar();menuBar.add(fielMenu);menuBar.add(editMenu);menuBar.add(formMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//创建两个框架,用作查找和替换foundFrame=new JFrame();replaceFrame=new JFrame();//创建两个文本框textField1=new JTextField(15);textField2=new JTextField(15);startButton=new utton("开始");startButton.addActionListener(listener); replaceButton=new utton("替换为"); replaceButton.addActionListener(listener);reallButton=new utton("全部替换");reallButton.addActionListener(listener);}//创建菜单项事件监听器ActionListener listener=new ActionListener() {publicvoid actionPerformed(ActionEvent e) {String name=e.getActionCommand();if(e.getSource() instanceof JMenuItem){if("新建".equals(name)){textArea.setText("");file=null;}if("打开".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}int returnVal=fileChooser.showOpenDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileReader reader=new FileReader(file); int len=(int)file.length();char[] array=newchar[len];reader.read(array,0,len);reader.close();textArea.setText(new String(array));}catch(Exception e_open){e_open.printStackTrace();}}}if("保存".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}int returnVal=fileChooser.showSaveDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileWriter writer=new FileWriter(file);writer.write(textArea.getText());writer.close();}catch (Exception e_save) {e_save.getStackTrace();}}if("退出".equals(name)){System.exit(0);}if("剪切".equals(name)){textArea.cut();}if("复制".equals(name)){textArea.copy();}if("粘贴".equals(name)){textArea.paste();}if("查找".equals(name)){value=textArea.getText();foundFrame.add(textField1,BorderLayout.CENTER); foundFrame.add(startButton,BorderLayout.SOUTH); foundFrame.setLocation(300,300);foundFrame.setTitle("查找");foundFrame.pack();foundFrame.setVisible(true);foundFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);}if("替换".equals(name)){value=textArea.getText();JLabel label1=new JLabel("查找容:");JLabel label2=new JLabel("替换为:");JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(2,2));JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,3)); replaceFrame.add(panel1,BorderLayout.NORTH);replaceFrame.add(panel2,BorderLayout.CENTER);panel1.add(label1);panel1.add(textField1);panel1.add(label2);panel1.add(textField2);panel2.add(startButton);panel2.add(replaceButton);panel2.add(reallButton);replaceFrame.setTitle("替换");replaceFrame.setLocation(300,300);replaceFrame.pack();replaceFrame.setVisible(true);replaceFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ;}if("开始".equals(name)||"下一个".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;startButton.setText("下一个");}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif")); foundFrame.dispose();}}if("替换为".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;textArea.replaceSelection(textField2.getText());}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif")); foundFrame.dispose();}}if("全部替换".equals(name)){String temp=textArea.getText();temp=temp.replaceAll(textField1.getText(),textField2.getTex t());textArea.setText(temp);}if("全选".equals(name)){textArea.selectAll();}if("字体".equals(name)){FontDialog fontDialog=newFontDialog(NotePad.this);fontDialog.setVisible(true);if(textArea.getFont()!=fontDialog.getFont()){ textArea.setFont(fontDialog.getFont());}}if("记事本……".equals(name)){AboutDialog aboutDialog=newAboutDialog(NotePad.this);aboutDialog.setVisible(true);}}};//创建字体设置对话面板,并添加相应事件监听器class FontDialog extends JDialog implements ItemListener, ActionListener, WindowListener{public JCheckBox Bold=new JCheckBox("Bold",false); public JCheckBox Italic=new JCheckBox("Italic",false); public List Size,Name;publicint FontName;publicint FontStyle;publicint FontSize;public utton OK=new utton("OK");public utton Cancel=new utton("Cancel");public JTextArea Text=new JTextArea("字体预览文本域\n0123456789\nAaBbCcXxYyZz");public FontDialog(JFrame owner) {super(owner,"字体设置",true);GraphicsEnvironmentg=GraphicsEnvironment.getLocalGraphicsEnvironment();String name[]=g.getAvailableFontFamilyNames(); Name=new List();Size=new List();FontName=0;FontStyle=0;FontSize=8;int i=0;Name.add("Default Value");for(i=0;i<name.length;i++)Name.add(name[i]);for(i=8;i<257;i++)Size.add(String.valueOf(i));this.setLayout(null);this.setBounds(250,200,480, 306); this.setResizable(false);OK.setFocusable(false);Cancel.setFocusable(false);Bold.setFocusable(false);Italic.setFocusable(false); Name.setFocusable(false);Size.setFocusable(false);Name.setBounds(10, 10, 212, 259); this.add(Name);Bold.setBounds(314, 10, 64, 22); this.add(Bold);Italic.setBounds(388, 10, 64, 22); this.add(Italic);Size.setBounds(232, 10, 64, 259); this.add(Size);Text.setBounds(306, 40, 157, 157); this.add(Text);OK.setBounds(306, 243, 74, 26); this.add(OK);Cancel.setBounds(390, 243, 74, 26); this.add(Cancel);Name.select(FontName);Size.select(FontSize);Text.setFont(getFont());Name.addItemListener(this);Size.addItemListener(this);Bold.addItemListener(this);Italic.addItemListener(this);OK.addActionListener(this); Cancel.addActionListener(this);this.addWindowListener(this);}publicvoid itemStateChanged(ItemEvent e) {Text.setFont(getFont());}publicvoid actionPerformed(ActionEvent e) {if(e.getSource()==OK){FontName=Name.getSelectedIndex();FontStyle=getStyle();FontSize=Size.getSelectedIndex();this.setVisible(false);}else cancel();}publicvoid windowClosing(WindowEvent e) {cancel();}public Font getFont(){if(Name.getSelectedIndex()==0) returnnew Font("新宋体",getStyle(),Size.getSelectedIndex()+8);elsereturnnewFont(Name.getSelectedItem(),getStyle(),Size.getSelectedIndex() +8);}publicvoid cancel(){Name.select(FontName);Size.select(FontSize);setStyle();Text.setFont(getFont());this.setVisible(false);}publicvoid setStyle(){if(FontStyle==0 || FontStyle==2) Bold.setSelected(false); else Bold.setSelected(true);if(FontStyle==0 || FontStyle==1) Italic.setSelected(false); else Italic.setSelected(true);}publicint getStyle(){int bold=0,italic=0;if(Bold.isSelected()) bold=1;if(Italic.isSelected()) italic=1;return bold+italic*2;}publicvoid windowActivated(WindowEvent arg0) {}publicvoid windowClosed(WindowEvent arg0) {}publicvoid windowDeactivated(WindowEvent arg0) {}publicvoid windowDeiconified(WindowEvent arg0) {}publicvoid windowIconified(WindowEvent arg0) {}publicvoid windowOpened(WindowEvent arg0) {}}//创建关于对话框class AboutDialog extends JDialog implements ActionListener{ public utton OK,Icon;public JLabel Name,Version,Author,Java;public JPanel Panel;AboutDialog(JFrame owner) {super(owner,"关于",true);OK=new utton("OK");Icon=new utton(new ImageIcon("icons\\edit.gif"));Name=new JLabel("Notepad");Version=new JLabel("Version 1.0");Java=new JLabel("JRE Version 6.0");Author=new JLabel("Copyright (c) 11-5-2012 By Jianmin Chen"); Panel=new JPanel();Color c=new Color(0,95,191);Name.setForeground(c);Version.setForeground(c);Java.setForeground(c);Author.setForeground(c);Panel.setBackground(Color.white);OK.setFocusable(false);this.setBounds(250,200,280, 180);this.setResizable(false);this.setLayout(null);Panel.setLayout(null);OK.addActionListener(this);Icon.setFocusable(false);Icon.setBorderPainted(false);Author.setFont(new Font(null,Font.PLAIN,11));Panel.add(Icon);Panel.add(Name);Panel.add(Version);Panel.add(Author);Panel.add(Java);this.add(Panel);this.add(OK);Panel.setBounds(0, 0, 280, 100);OK.setBounds(180, 114, 72, 26);Name.setBounds(80, 10, 160, 20);Version.setBounds(80, 27, 160, 20);Author.setBounds(15, 70, 250, 20);Java.setBounds(80, 44, 160, 20);Icon.setBounds(16, 14, 48, 48);}publicvoid actionPerformed(ActionEvent e) {this.setVisible(false);}}}//创建记事本publicclass ChenJianmin {publicstaticvoid main(String[] args){EventQueue.invokeLater(new Runnable() {publicvoid run() {NotePad notePad=new NotePad();notePad.setTitle("记事本");notePad.setVisible(true);notePad.setBounds(100,100,800,600);notePad.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}});}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

/*** 作品:记事本* 作者:**** 功能:简单的文字编辑*/import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;class NotePad extends JFrame{private JMenuBar menuBar;private JMenu fielMenu,editMenu,formMenu,aboutMenu;private JMenuItemnewMenuItem,openMenuItem,saveMenuItem,exitMenuItem;private JMenuItemcutMenuItem,copyMenuItem,pasteMenuItem,foundItem,replaceItem,s electAll;private JMenuItem font,about;private JTextArea textArea;private JFrame foundFrame,replaceFrame;private JCheckBoxMenuItem wrapline;private JTextField textField1=new JTextField(15);private JTextField textField2=new JTextField(15);private JButton startButton,replaceButton,reallButton;int start=0;String value;File file=null;JFileChooser fileChooser=new JFileChooser();boolean wrap=false;public NotePad(){//创建文本域textArea=new JTextArea();add(new JScrollPane(textArea),BorderLayout.CENTER);//创建文件菜单及文件菜单项fielMenu=new JMenu("文件");fielMenu.setFont(new Font("微软雅黑",0,15));newMenuItem=new JMenuItem("新建",newImageIcon("icons\\new24.gif"));newMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_N,InputEvent.CTRL_MASK));newMenuItem.addActionListener(listener);openMenuItem=new JMenuItem("打开",newImageIcon("icons\\open24.gif"));openMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_O,InputEvent.CTRL_MASK));openMenuItem.addActionListener(listener);saveMenuItem=new JMenuItem("保存",newImageIcon("icons\\save.gif"));saveMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_S,InputEvent.CTRL_MASK));saveMenuItem.addActionListener(listener);exitMenuItem=new JMenuItem("退出",newImageIcon("icons\\exit24.gif"));exitMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_E,InputEvent.CTRL_MASK));exitMenuItem.addActionListener(listener);//创建编辑菜单及菜单项editMenu=new JMenu("编辑");editMenu.setFont(new Font("微软雅黑",0,15));cutMenuItem=new JMenuItem("剪切",newImageIcon("icons\\cut24.gif"));cutMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_X,InputEvent.CTRL_MASK));cutMenuItem.addActionListener(listener);copyMenuItem=new JMenuItem("复制",newImageIcon("icons\\copy24.gif"));copyMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_C,InputEvent.CTRL_MASK));copyMenuItem.addActionListener(listener);pasteMenuItem=new JMenuItem("粘贴",newImageIcon("icons\\paste24.gif"));pasteMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEven t.VK_V,InputEvent.CTRL_MASK));pasteMenuItem.addActionListener(listener);foundItem=new JMenuItem("查找");foundItem.setFont(new Font("微软雅黑",Font.BOLD,13));foundItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _F,InputEvent.CTRL_MASK));foundItem.addActionListener(listener);replaceItem=new JMenuItem("替换");replaceItem.setFont(new Font("微软雅黑",Font.BOLD,13));replaceItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_R,InputEvent.CTRL_MASK));replaceItem.addActionListener(listener);selectAll=new JMenuItem("全选");selectAll.setFont(new Font("微软雅黑",Font.BOLD,13));selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _A,InputEvent.CTRL_MASK));selectAll.addActionListener(listener);//创建格式菜单及菜单项formMenu=new JMenu("格式");formMenu.setFont(new Font("微软雅黑",0,15));wrapline=new JCheckBoxMenuItem("自动换行");wrapline.setFont(new Font("微软雅黑",Font.BOLD,13));wrapline.addActionListener(listener);wrapline.addChangeListener(new ChangeListener() {public void stateChanged(ChangeEvent e) {if(wrapline.isSelected()){textArea.setLineWrap(true);}elsetextArea.setLineWrap(false);}});font=new JMenuItem("字体");font.setFont(new Font("微软雅黑",Font.BOLD,13)); font.addActionListener(listener);//创建关于菜单aboutMenu=new JMenu("关于");aboutMenu.setFont(new Font("微软雅黑",0,15)); about=new JMenuItem("记事本……");about.setFont(new Font("微软雅黑",Font.BOLD,13)); about.addActionListener(listener);//添加文件菜单项fielMenu.add(newMenuItem);fielMenu.add(openMenuItem);fielMenu.add(saveMenuItem);fielMenu.addSeparator();fielMenu.add(exitMenuItem);//添加编辑菜单项editMenu.add(cutMenuItem);editMenu.add(copyMenuItem);editMenu.add(pasteMenuItem);editMenu.add(foundItem);editMenu.add(replaceItem);editMenu.addSeparator();editMenu.add(selectAll);//添加格式菜单项formMenu.add(wrapline);formMenu.add(font);//添加关于菜单项aboutMenu.add(about);//添加菜单menuBar=new JMenuBar();menuBar.add(fielMenu);menuBar.add(editMenu);menuBar.add(formMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//创建两个框架,用作查找和替换foundFrame=new JFrame();replaceFrame=new JFrame();//创建两个文本框textField1=new JTextField(15);textField2=new JTextField(15);startButton=new JButton("开始");startButton.addActionListener(listener);replaceButton=new JButton("替换为");replaceButton.addActionListener(listener);reallButton=new JButton("全部替换");reallButton.addActionListener(listener);}//创建菜单项事件监听器ActionListener listener=new ActionListener() {public void actionPerformed(ActionEvent e) {String name=e.getActionCommand();if(e.getSource() instanceof JMenuItem){if("新建".equals(name)){textArea.setText("");file=null;}if("打开".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}intreturnVal=fileChooser.showOpenDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileReader reader=new FileReader(file);int len=(int)file.length();char[] array=new char[len];reader.read(array,0,len);reader.close();textArea.setText(new String(array));}catch(Exception e_open){e_open.printStackTrace();}}}if("保存".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}intreturnVal=fileChooser.showSaveDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileWriter writer=new FileWriter(file);writer.write(textArea.getText());writer.close();}catch (Exception e_save) {e_save.getStackTrace();}}if("退出".equals(name)){System.exit(0);}if("剪切".equals(name)){textArea.cut();}if("复制".equals(name)){textArea.copy();}if("粘贴".equals(name)){textArea.paste();}if("查找".equals(name)){value=textArea.getText();foundFrame.add(textField1,BorderLayout.CENTER);foundFrame.add(startButton,BorderLayout.SOUTH);foundFrame.setLocation(300,300);foundFrame.setTitle("查找");foundFrame.pack();foundFrame.setVisible(true);foundFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );}if("替换".equals(name)){value=textArea.getText();JLabel label1=new JLabel("查找内容:");JLabel label2=new JLabel("替换为:");JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(2,2));JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,3));replaceFrame.add(panel1,BorderLayout.NORTH);replaceFrame.add(panel2,BorderLayout.CENTER);panel1.add(label1);panel1.add(textField1);panel1.add(label2);panel1.add(textField2);panel2.add(startButton);panel2.add(replaceButton);panel2.add(reallButton);replaceFrame.setTitle("替换");replaceFrame.setLocation(300,300);replaceFrame.pack();replaceFrame.setVisible(true);replaceFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLO SE);}if("开始".equals(name)||"下一个".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;startButton.setText("下一个");}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif"));foundFrame.dispose();}}if("替换为".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;textArea.replaceSelection(textField2.getText());}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif"));foundFrame.dispose();}}if("全部替换".equals(name)){String temp=textArea.getText();temp=temp.replaceAll(textField1.getText(),textField2.getTex t());textArea.setText(temp);}if("全选".equals(name)){textArea.selectAll();}if("字体".equals(name)){FontDialog fontDialog=newFontDialog(NotePad.this);fontDialog.setVisible(true);if(textArea.getFont()!=fontDialog.getFont()){textArea.setFont(fontDialog.getFont());}}if("记事本……".equals(name)){AboutDialog aboutDialog=newAboutDialog(NotePad.this);aboutDialog.setVisible(true);}}};//创建字体设置对话面板,并添加相应事件监听器class FontDialog extends JDialog implements ItemListener, ActionListener, WindowListener{public JCheckBox Bold=new JCheckBox("Bold",false);public JCheckBox Italic=new JCheckBox("Italic",false);public List Size,Name;public int FontName;public int FontStyle;public int FontSize;public JButton OK=new JButton("OK");public JButton Cancel=new JButton("Cancel");public JTextArea Text=new JTextArea("字体预览文本域\n0123456789\nAaBbCcXxYyZz");public FontDialog(JFrame owner) {super(owner,"字体设置",true);GraphicsEnvironmentg=GraphicsEnvironment.getLocalGraphicsEnvironment();String name[]=g.getAvailableFontFamilyNames();Name=new List();Size=new List();FontName=0;FontStyle=0;FontSize=8;int i=0;Name.add("Default Value");for(i=0;i<name.length;i++)Name.add(name[i]);for(i=8;i<257;i++)Size.add(String.valueOf(i));this.setLayout(null);this.setBounds(250,200,480, 306);this.setResizable(false);OK.setFocusable(false);Cancel.setFocusable(false);Bold.setFocusable(false);Italic.setFocusable(false);Name.setFocusable(false);Size.setFocusable(false);Name.setBounds(10, 10, 212, 259);this.add(Name);Bold.setBounds(314, 10, 64, 22);this.add(Bold);Italic.setBounds(388, 10, 64, 22);this.add(Italic);Size.setBounds(232, 10, 64, 259);this.add(Size);Text.setBounds(306, 40, 157, 157);this.add(Text);OK.setBounds(306, 243, 74, 26);this.add(OK);Cancel.setBounds(390, 243, 74, 26);this.add(Cancel);Name.select(FontName);Size.select(FontSize);Text.setFont(getFont());Name.addItemListener(this);Size.addItemListener(this);Bold.addItemListener(this);Italic.addItemListener(this);OK.addActionListener(this);Cancel.addActionListener(this);this.addWindowListener(this);}public void itemStateChanged(ItemEvent e) {Text.setFont(getFont());}public void actionPerformed(ActionEvent e) {if(e.getSource()==OK){FontName=Name.getSelectedIndex();FontStyle=getStyle();FontSize=Size.getSelectedIndex();this.setVisible(false);}else cancel();}public void windowClosing(WindowEvent e) {cancel();}public Font getFont(){if(Name.getSelectedIndex()==0) return new Font("新宋体",getStyle(),Size.getSelectedIndex()+8);else return newFont(Name.getSelectedItem(),getStyle(),Size.getSelectedIndex() +8);}public void cancel(){Name.select(FontName);Size.select(FontSize);setStyle();Text.setFont(getFont());this.setVisible(false);}public void setStyle(){if(FontStyle==0 || FontStyle==2)Bold.setSelected(false);else Bold.setSelected(true);if(FontStyle==0 || FontStyle==1)Italic.setSelected(false);else Italic.setSelected(true);}public int getStyle(){int bold=0,italic=0;if(Bold.isSelected()) bold=1;if(Italic.isSelected()) italic=1;return bold+italic*2;}public void windowActivated(WindowEvent arg0) {}public void windowClosed(WindowEvent arg0) {}public void windowDeactivated(WindowEvent arg0) {}public void windowDeiconified(WindowEvent arg0) {}public void windowIconified(WindowEvent arg0) {}public void windowOpened(WindowEvent arg0) {} }//创建关于对话框class AboutDialog extends JDialog implements ActionListener{ public JButton OK,Icon;public JLabel Name,Version,Author,Java;public JPanel Panel;AboutDialog(JFrame owner) {super(owner,"关于",true);OK=new JButton("OK");Icon=new JButton(new ImageIcon("icons\\edit.gif"));Name=new JLabel("Notepad");Version=new JLabel("Version 1.0");Java=new JLabel("JRE Version 6.0");Author=new JLabel("Copyright (c) 11-5-2012 By Jianmin Chen");Panel=new JPanel();Color c=new Color(0,95,191);Name.setForeground(c);Version.setForeground(c);Java.setForeground(c);Author.setForeground(c);Panel.setBackground(Color.white);OK.setFocusable(false);this.setBounds(250,200,280, 180);this.setResizable(false);this.setLayout(null);Panel.setLayout(null);OK.addActionListener(this);Icon.setFocusable(false);Icon.setBorderPainted(false);Author.setFont(new Font(null,Font.PLAIN,11));Panel.add(Icon);Panel.add(Name);Panel.add(Version);Panel.add(Author);Panel.add(Java);this.add(Panel);this.add(OK);Panel.setBounds(0, 0, 280, 100);OK.setBounds(180, 114, 72, 26);Name.setBounds(80, 10, 160, 20);Version.setBounds(80, 27, 160, 20);Author.setBounds(15, 70, 250, 20);Java.setBounds(80, 44, 160, 20);Icon.setBounds(16, 14, 48, 48);}public void actionPerformed(ActionEvent e) { this.setVisible(false);}}}//创建记事本public class ChenJianmin {public static void main(String[] args){EventQueue.invokeLater(new Runnable() {public void run() {NotePad notePad=new NotePad();notePad.setTitle("记事本");notePad.setVisible(true);notePad.setBounds(100,100,800,600);notePad.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}});}}。

相关文档
最新文档