導航:首頁 > 編程語言 > java設計記事本

java設計記事本

發布時間:2023-10-20 13:15:32

『壹』 java編寫簡單記事本

方法/步驟
下載JDK,並安裝成功,CMD測試Java環境安裝成功。出現如下提示則Java環境安裝成功

打開mycelipse進入主界面,點擊左上角file--new---java project,新建一個Java項目,項目名字任意取,這里我取名為note--然後點擊完成,創建Java項目

然後右鍵項目下的src--new---package,新建一個包,包名我定為notetest,然後點擊完成

然後右鍵我們建立好的包notetest--new--class,包名為Note,點擊完成

首先我們想導入工程所需要的包,以便編寫程序時進行調用
package notepad;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;

首先定義好編寫程序時變數,我們設為成員變數方便以後調用
public class Notepad{
//屏幕解析度
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
//窗體
private Frame frm ;

//顯示內容多行文本
private TextArea notetext;
//記事本菜單
private MenuBar mb;
//菜單
private Menu m ;
//菜單項
private MenuItem open,save;

為程序創建組件--Frame--菜單欄目--文本框TextArea
public Notepad(){init();}

private void init(){
frm = new Frame("模擬記事本");

//設置菜單
mb = new MenuBar();
m = new Menu("文件");

//顯示文件的地方
notetext = new TextArea();
notetext.setBounds(30, 50, 750, 500);
frm.add(notetext);
myEvent();

為控制項和按鈕添加監聽事件
private void myEvent() {
//打開菜單的事件處理
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//判斷路徑和文件名是否為空 如果為空結束程序
if(dir == null || name == null)

//如果不為空講路徑名和文件名封裝到File對象里

file = new File(dir,name);

//使用字元緩沖讀取文件

BufferedReader bfr = null;

try {
bfr = new BufferedReader(new FileReader(file));
});
save.addActionListener(new ActionListener(){

//獲取路徑和文件名

String dir =fd.getDirectory();
String name = fd.getFile();
//如果不為空講路徑名和文件名封裝到File對象里
file = new File(dir,name);
}

BufferedWriter bfr= null;
}

});
}
}

然後創建主方法,開始測試程序,新建一個NoteDemo類
package notepad;

public class NoteDemo {
public static void main(String[] args) {
new Notepad();
}

}

『貳』 用JAVA編個簡單的記事本程序

import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;

class Editor extends Frame implements ActionListener,ItemListener
{
// Date date=new Date();
int n1;String str="";int k=0;String st1,st2;
JTextArea ta=new JTextArea(50,50);
Dialog dialog,dialog1;
Choice ce1,ce2,ce3;
Button btn1,btn2,btn3;Panel p1=new Panel();
Panel p2=new Panel();Panel p3=new Panel();Panel p4=new Panel();
public Editor (String s)
{
super ("記事本編輯板");
ImageIcon YouImg = new ImageIcon("iconimage.jpg");
setIconImage(YouImg.getImage());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}

});
setBounds(50,35,700,500);

MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu file=new Menu("文件(F)");Menu edit=new Menu("編輯(E)");Menu help=new Menu("幫助(H)");
Menu pattern=new Menu("格式(P)");Menu time=new Menu("時間(T)");
MenuItem exit=new MenuItem("退出",new MenuShortcut(KeyEvent.VK_Q));
MenuItem tdate=new MenuItem("日期/時間",new MenuShortcut(KeyEvent.VK_D));
MenuItem renew=new MenuItem("新建", new MenuShortcut(KeyEvent.VK_N));
MenuItem save=new MenuItem("保存", new MenuShortcut(KeyEvent.VK_S));
MenuItem open=new MenuItem("打開",new MenuShortcut(KeyEvent.VK_O));
MenuItem =new MenuItem("復制",new MenuShortcut(KeyEvent.VK_C));
MenuItem paste=new MenuItem("粘貼",new MenuShortcut(KeyEvent.VK_V));
MenuItem cut=new MenuItem("剪切",new MenuShortcut(KeyEvent.VK_X));
MenuItem helptopic=new MenuItem("主題",new MenuShortcut(KeyEvent.VK_T));
helptopic.addActionListener(this);
dialog=new Dialog(this, "字體設置");dialog.setSize(300,300);
dialog1=new Dialog(this, "幫助主題");dialog1.setBounds(250,100,300,400);
dialog.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dialog.setVisible(false);}
});
dialog1.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dialog1.setVisible(false);}
});
//dialog.setBackground(Color.WHITE);
dialog.setLayout(null);dialog.setBounds(170,150,450,300);
Label L1=new Label("字體(F)");Label L2=new Label("字形(Y)");
Label L3=new Label("大小(S)");TextArea ta1=new TextArea(5,5);
ta1=new TextArea("至於記事本的主題嘛,因為本人的水平有限, 所有不能為大家作過多的指導,望大家見諒!"); //在這里我想加一個文本框用來放幫助信息。

ce1=new Choice();ce2=new Choice();
ce3=new Choice();
btn1=new Button("確定");btn2=new Button("取消");btn1.addActionListener(this);btn2.addActionListener(this);
btn3=new Button("顏色");
btn3.addActionListener(this);

ce1.add("華文行楷");ce1.add("華文中宋");ce1.add("華文新魏");ce1.add("華文細黑");ce1.add("宋體");ce1.add("方正姚體");
ce1.add("幼圓");ce1.add("隸書");ce1.add("楷體-GB2312");ce1.add("華文行楷");ce1.add("華文彩雲");ce1.add("仿宋-GB2312");
ce2.add("粗體");ce2.add("斜體");ce2.add("常規");
for(int n1=0;n1<=100;n1++)
{ce3.add(""+n1);}
dialog.add(p1);p1.setBounds(5,30,440,35);p1.setLayout( null);//p1.setBackground(Color.red);
dialog.add(p2);p2.setBounds(5,65,440,27);dialog.add(p3);p3.setBounds(5,90,440,40);//p4.setBounds(5,120,440,138);
p1.setLayout( null);
p1.add(L1);L1.setBounds(5,15,50,25);p1.add(L2);L2.setBounds(150,15,50,25);
p1.add(L3);L3.setBounds(250,15,50,25);p2.setLayout( null);//p2.setBackground(Color.yellow);
p2.add(ce1);ce1.setBounds(5,0,130,25);p2.add(ce2);ce2.setBounds(160,0,90,25);p2.add(ce3);ce3.setBounds(260,0,75,25);
p2.add(btn1);btn1.setBounds(360,0,75,25);
p3.setLayout( null);p3.add(btn2);btn2.setBounds(360,10,75,25);p3.add(btn3);btn3.setBounds(160,10,75,25);
dialog.add(p4);p4.setBackground(Color.yellow);p4.setBounds(5,120,440,138);
dialog1.add(ta1);
//設置字體的下拉情況
MenuItem Font=new MenuItem("字體");//給字體加監聽器
Font.addActionListener(this);
MenuItem Replace=new MenuItem("替換"); MenuItem Seek=new MenuItem("查找");
//首要添加組件的情況
mb.add(file);mb.add(edit);mb.add(pattern);mb.add(time);mb.add(help);
file.add(renew);file.addSeparator();file.add(open);time.add(tdate);
file.addSeparator(); file.add(exit);file.addSeparator();file.add(save);
edit.add(); edit.addSeparator();edit.add(paste);edit.addSeparator();edit.add(cut);
pattern.add(Font); pattern.add(Replace);
pattern.add(Seek);help.add(helptopic);
//給必要的組件加上監聽器
renew.addActionListener( this);tdate.addActionListener(this);
open.addActionListener(this); save.addActionListener(this);exit.addActionListener(this);
cut.addActionListener(this);.addActionListener(this);paste.addActionListener(this);
ce1.addItemListener(this);ce2.addItemListener(this);ce3.addItemListener(this);
//添加必要的組件
add(ta,"Center");ta.setBackground(new Color(249,255,234));
setSize(700,500);
setVisible(true);
this.validate() ;

}

public void itemStateChanged(ItemEvent e) {
if (ce2.getSelectedItem().equals("粗體"))
{ k=1;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
if (ce2.getSelectedItem().equals("斜體"))
{ k=2;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
if (ce2.getSelectedItem().equals("常規"))
{ k=3;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
}

public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("新建"))
{System.out.println("new ");
ta.setText("");}
if(e.getActionCommand().equals("退出"))
{ System.exit(0);}
try
{
if(e.getActionCommand().equals("打開"))
openText();
if(e.getActionCommand().equals("保存"))
saveText();
}catch(IOException e1){}
if(e.getActionCommand().equals("復制"))
{ str=ta.getSelectedText();}
if(e.getActionCommand().equals("粘貼"))
{ ta.insert(str,ta.getCaretPosition());}
if(e.getActionCommand().equals("剪切"))
{str=ta.getSelectedText();ta.replaceRange("",ta.getSelectionStart(),ta.getSelectionEnd());

}
if(e.getActionCommand().equals("字體"))
{dialog.setVisible(true);}
if(e.getActionCommand().equals("主題"))
{dialog1.setVisible(true);}
if(e.getActionCommand().equals("顏色"))
{
Color clr=JColorChooser.showDialog(this,"顏色對話框",null);
ta.setForeground(clr);
}

if(e.getSource()==btn2)
dialog.setVisible(false);
if(e.getSource()==btn1)
{
if(k==1)
{ ta.setFont(new Font(st1,Font.BOLD,Integer.parseInt(st2)));}
if(k==2)
{ ta.setFont(new Font(st1,Font.ITALIC,Integer.parseInt(st2)));}
if(k==3)
{ ta.setFont(new Font(st1,Font.PLAIN,Integer.parseInt(st2)));}
dialog.setVisible(false);
}

//if (e.getActionCommand().equals("日期/時間"))
//ta.setText(ta.getText()+""+date);
if(e.getActionCommand().equals("日期/時間"))
{
Calendar c1 =Calendar.getInstance();
int y = c1.get(Calendar.YEAR);
int m = c1.get(Calendar.MONTH);
int d = c1.get(Calendar.DATE);
int h = c1.get(Calendar.HOUR);
int m1 = c1.get(Calendar.MINUTE);
int m2 = m+1;
ta.setText(ta.getText()+""+(y+"年"+m2+"月"+d+"日"+h+":"+m1));
}

}

public void openText() throws IOException
{
FileDialog fd=new FileDialog(this,"打開文件對話框",FileDialog.LOAD);
fd.setVisible(true);FileInputStream fis=new FileInputStream(fd.getDirectory()+fd.getFile());
ta.setText("");
int n=0;
while((n=fis.read())!=-1)
ta.append(""+(char)n);
fis.close();
}
public void saveText() throws IOException
{
FileDialog fd=new FileDialog(this,"打開文件對話框",FileDialog.SAVE);
fd.setVisible(true);
FileOutputStream out=new FileOutputStream(fd.getDirectory()+fd.getFile()+".txt");
String str=ta.getText();

String str1=ta.getText();
for(int n=0;n<str.length();n++)
out.write((byte)str.charAt(n));
out.close();
}

public static void main(String[] args)
{
Editor f=new Editor(" 記事本程序");
//添加時間代碼
Date date=new Date();
System.out.print(date);
/*Calendar now=Calendar.getInstance();
int year=now.get(Calendar.YEAR);
int month=now.get(Calendar.MONTH)+1;
int day=now.get(Calendar.DATE);
System.out.print(year+"年"+month+"月"+day+"日");

int week=now.get(Calendar.DAY_OF_WEEK);
String str="日一二三四五六";//星期1-7
int i=2*(week-1);
System.out.println("星期"+str.substring(i,i+2));//對應中文的下標*/

}

class dialog extends Dialog
{

public dialog()
{
super(dialog, "字體設置");

class Mycanvas extends Canvas
{
Toolkit tk;
Image img;
Mycanvas()
{
setSize(440,138);
tk=getToolkit();
img=tk.getImage("photo.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,5,120,440,138,this);
}
}
}
}
}

『叄』 如何用JAVA程序編寫一個記事本

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.UndoManager;
import java.util.Date;
import java.text.SimpleDateFormat;

public class Notepad extends JFrame {
// 菜單
JMenuBar menub = new JMenuBar();
// 顯示純文本的多行區域
JTextArea text = new JTextArea();
JMenu files = new JMenu("文件(F)");
JMenu edit = new JMenu("編輯(E)");
JMenu formats = new JMenu("格式(O)");
JMenu help = new JMenu("幫助(H)");
JMenuItem newFile = new JMenuItem("新建(N)");
JMenuItem open = new JMenuItem("打開(O)");
JMenuItem save = new JMenuItem("保存(S)");
JMenuItem saveAs = new JMenuItem("另存為(A)");
JMenuItem exit = new JMenuItem("退出(X)");
JMenuItem undo = new JMenuItem("撤銷(U)");
JMenuItem cut = new JMenuItem("剪切(T)");
JMenuItem = new JMenuItem("復制(C)");
JMenuItem paste = new JMenuItem("粘貼(P)");
JMenuItem selectAll = new JMenuItem("全選(A)");
JMenuItem timeDate = new JMenuItem("時間/日期(D)");
JCheckBoxMenuItem lineWrap = new JCheckBoxMenuItem("自動換行(M)");
JMenuItem fonts = new JMenuItem("字體");
JMenuItem about = new JMenuItem("關於記事本(A)");
JFrame th = this;
String name;
String openedPath = null;
boolean opened = false;
boolean reworked = false;
UndoManager undoManager = new UndoManager();

// 初始化窗體
public Notepad(String name) {
super(name);
this.name = name;
int x, y;
// 得到用戶屏幕大小
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
x = (size.width - 600) / 2;
y = (size.height - 400) / 2;
setSize(600, 400);
// 讓程序界面顯示在屏幕中央
setLocation(x, y);
// 將此窗口的最小大小設置為一個常量值。
setMinimumSize(new Dimension(250, 150));
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

// 初始化布局
void init() {
files.setMnemonic('F');
edit.setMnemonic('E');
formats.setMnemonic('O');
help.setMnemonic('H');
newFile.setMnemonic('N');
open.setMnemonic('O');
save.setMnemonic('S');
saveAs.setMnemonic('A');
exit.setMnemonic('X');
undo.setMnemonic('U');
cut.setMnemonic('T');
.setMnemonic('C');
paste.setMnemonic('P');
selectAll.setMnemonic('A');
timeDate.setMnemonic('D');
lineWrap.setMnemonic('M');
about.setMnemonic('A');
// 為控制項添加助記符
newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
InputEvent.CTRL_MASK));
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
InputEvent.CTRL_MASK));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_MASK));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
InputEvent.CTRL_MASK));
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
InputEvent.CTRL_MASK));
.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
InputEvent.CTRL_MASK));
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
InputEvent.CTRL_MASK));
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_MASK));
// 為控制項添加快捷鍵
timeDate.setAccelerator(KeyStroke.getKeyStroke("F5"));

files.add(newFile);
files.add(open);
files.add(save);
files.add(saveAs);
files.addSeparator();
files.add(exit);
edit.add(undo);
edit.addSeparator();
edit.add(cut);
edit.add();
edit.add(paste);
edit.addSeparator();
edit.add(selectAll);
edit.add(timeDate);
formats.add(lineWrap);
formats.add(fonts);
help.add(about);

menub.add(files);
menub.add(edit);
menub.add(formats);
menub.add(help);
setJMenuBar(menub);
getContentPane().add(new JScrollPane(text));

Listen listen = new Listen();
Listen1 listen1 = new Listen1();
// 為控制項添加事件偵聽器
newFile.addActionListener(listen);
undo.addActionListener(listen);
open.addActionListener(listen);
save.addActionListener(listen);
saveAs.addActionListener(listen);
exit.addActionListener(listen);
cut.addActionListener(listen);
.addActionListener(listen);
paste.addActionListener(listen);
selectAll.addActionListener(listen);
timeDate.addActionListener(listen);
lineWrap.addActionListener(listen);
about.addActionListener(listen);
open.addActionListener(listen1);
save.addActionListener(listen1);
saveAs.addActionListener(listen1);
// 暫時沒有實現的功能 :設置字體
//undo功能沒有實現
fonts.setEnabled(false);

}
class Listen implements ActionListener {
// 實現用於一般操作的事件偵聽器
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == newFile) {
text.setText("");
// 設置標題
th.setTitle(name);
openedPath = null;
opened = false;
} else if (source == exit)
setVisible(false);
else if (source == undo)
try {
//此功能沒有實現 撤銷要用棧?
// undo.setEnabled(undoManager.canUndo());
undoManager.undo();
} catch (CannotRedoException cre) {
cre.printStackTrace();
}
else if (source == selectAll)
text.selectAll();
else if (source == cut)
text.cut();
else if (source == )
text.();
else if (source == paste)
text.paste();
else if (source == lineWrap)
// 設置文本區的換行策略(獲取文本區的換行策略)
text.setLineWrap(!text.getLineWrap());
else if (source == about) {
String message = "--------\n版本:1.0\n作者:時超" +
"\n撤銷功能要用堆棧存貯操作" +
"\n還有字體格式"+
"\n暫時沒有實現" +
"\n\n感謝您的使用";
JOptionPane.showMessageDialog(th, message, "關於",
JOptionPane.PLAIN_MESSAGE);
} else if (source == timeDate) {
Date nowTime = new Date();
SimpleDateFormat times = new SimpleDateFormat(
"HH:mm yyyy-MM-dd");
text.insert(times.format(nowTime), text.getCaretPosition());
}
}
}
class Listen1 implements ActionListener {
// 實現用於對文件進行操作的事件偵聽器
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
// 打開文件事件
if (source == open) {
// 顯示對話窗口 以便選擇文件
FileDialog openFile = new FileDialog(th, "打開文件",
FileDialog.LOAD);
openFile.setVisible(true);
// 獲取文件路徑
String filePath = openFile.getDirectory() + openFile.getFile();
try {
FileInputStream fis = new FileInputStream(filePath);
byte[] content = new byte[fis.available()];
fis.read(content);
text.setText(new String(content));
// 設置 TextComponent 的文本插入符的位置
text.setCaretPosition(0);
if (openFile.getFile() != null) {
th.setTitle(openFile.getFile() + name);
openedPath = filePath;
opened = true;
}
fis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
opened = true;
}
// 保存及另存為事件
else if (source == save || source == saveAs) {
String savePath = openedPath;
if (savePath == null || source == saveAs) {
// 如果 mode 的值為 LOAD,那麼文件對話框將查找要讀取的文件,所顯示的文件是當前目錄中的文件
// 如果 mode 的值為 SAVE,則文件對話框將查找要寫入文件的位置。
FileDialog saveFile = new FileDialog(th, "保存文件",
FileDialog.SAVE);
saveFile.setVisible(true);
savePath = saveFile.getDirectory() + saveFile.getFile();
}
try {
FileOutputStream fos = new FileOutputStream(savePath);
fos.write(text.getText().getBytes());
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if (source == save)
openedPath = savePath;
}
}
}
public static void main(String[] args) {
try {
// 使用當前線程的上下文類載入器載入給定類名稱所指定的 LookAndFeel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("Couldn't use the system look and feel:" + e);
}
String name = ("--記事本 版本1.0--");
Notepad note = new Notepad(name);
note.init();
note.setVisible(true);
}
}

『肆』 用java編寫記事本程序,可以實現新建、打開、保存、退出、復制、粘貼、剪切、全選。

import javax.swing.*;
import javax.swing.filechooser.FileFilter;

import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;

public class MyText extends JFrame implements ActionListener{
private JLabel lb1;
private JMenuBar mb;
private JMenu 文件, 編輯, 格式, 幫助;
private JMenuItem 新建, 打開, 保存, 退出, 復制, 粘貼, 剪切, 全選, 字體, 關於;
private JTextArea editorArea;
private boolean isDirty = false;
private String strFileName = "未命名";
private static final String EDITOR_NAME = "MyText";

public MyText() {
super();
mb = new JMenuBar();
文件 = new JMenu("文件");
編輯 = new JMenu("編輯");
格式 = new JMenu("格式");
幫助 = new JMenu("幫助");
新建 = new JMenuItem("新建");
新建.addActionListener(this);
打開 = new JMenuItem("打開");
打開.addActionListener(this);
保存 = new JMenuItem("保存");
保存.addActionListener(this);
退出 = new JMenuItem("退出");
退出.addActionListener(this);
復制 = new JMenuItem("復制");
復制.addActionListener(this);
粘貼 = new JMenuItem("粘貼");
粘貼.addActionListener(this);
剪切 = new JMenuItem("剪切");
剪切.addActionListener(this);
全選 = new JMenuItem("全選");
全選.addActionListener(this);
字體 = new JMenuItem("字體");
字體.addActionListener(this);
關於 = new JMenuItem("關於");
關於.addActionListener(this);
mb.add(文件);
mb.add(編輯);
mb.add(格式);
mb.add(幫助);
文件.add(新建);
文件.add(打開);
文件.add(保存);
文件.add(退出);
編輯.add(復制);
編輯.add(粘貼);
編輯.add(剪切);
編輯.add(全選);
格式.add(字體);
幫助.add(關於);
setJMenuBar(mb);

Container container = getContentPane();
editorArea = new JTextArea();
editorArea.setLineWrap(true);
editorArea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(!isDirty()){
setDirty(true);
}
}
});
JScrollPane scrollPane = new JScrollPane(editorArea);
container.add(scrollPane);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
dispose();
}
});
setTitle(formatEditorTitle());
setSize(600, 400);
setVisible(true);
}

private boolean isDirty() {
return isDirty;
}

private void setDirty(boolean isDirty) {
this.isDirty = isDirty;
setTitle(formatEditorTitle());
}

public static void main(String args[]) {
@SuppressWarnings("unused")
MyText app = new MyText();
}

public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem)e.getSource();
if(item.equals(新建)){
if(isDirty()){
int ret = JOptionPane.showConfirmDialog(getContentPane(), "文件內容已經變動,是否保存?", "MyText", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if(ret == JOptionPane.OK_OPTION){
saveFile();
}else if(ret == JOptionPane.CANCEL_OPTION || ret == JOptionPane.CLOSED_OPTION){
return;
}
}
clearEditorArea();
setDirty(false);
}else if(item.equals(打開)){
if(isDirty()){
int ret = JOptionPane.showConfirmDialog(getContentPane(), "文件內容已經變動,是否保存?", "MyText", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if(ret == JOptionPane.OK_OPTION){
saveFile();
}else if(ret == JOptionPane.CANCEL_OPTION || ret == JOptionPane.CLOSED_OPTION){
return;
}
}
openFile();
}else if(item.equals(保存)){
saveFile();
}else if(item.equals(退出)){
dispose();
}else if(item.equals(復制)){
editorArea.();
}else if(item.equals(剪切)){
editorArea.cut();
}else if(item.equals(粘貼)){
editorArea.paste();
}else if(item.equals(全選)){
editorArea.selectAll();
}else if(item.equals(字體)){
FontDialog font = new FontDialog(this, editorArea.getFont());
editorArea.setFont(font.getSelectedFont());
}else if(item.equals(關於)){
AboutDialog about = new AboutDialog(this);
about.setVisible(true);
}
}

private String getFileName() {
return strFileName;
}

private void setFileName(String strFileName) {
this.strFileName = strFileName;
}

public String formatEditorTitle(){
StringBuffer strFileNm = new StringBuffer(getFileName());
strFileNm.append(isDirty()?"*":"");
strFileNm.append(" - ");
strFileNm.append(EDITOR_NAME);
return strFileNm.toString();
}

private void clearEditorArea(){
editorArea.selectAll();
editorArea.replaceSelection("");
}

private void openFile(){
JFileChooser openDialog = new JFileChooser();
openDialog.setFileFilter(new TxtFileFilter());
if(openDialog.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION){
File file = openDialog.getSelectedFile();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String buff = br.readLine();
clearEditorArea();
while(buff != null){
editorArea.append(buff);
editorArea.append("\n");
buff = br.readLine();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally{
try{
if(br != null)
br.close();
} catch (IOException ioe){
ioe.printStackTrace();
}
}
}
}

private void saveFile(){
JFileChooser saveDialog = new JFileChooser();
saveDialog.setFileFilter(new TxtFileFilter());
if(saveDialog.showSaveDialog(getContentPane()) == JFileChooser.APPROVE_OPTION){
File file = saveDialog.getSelectedFile();
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(file));
String buff = editorArea.getText();
bw.write(buff);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally{
try{
if(bw != null)
bw.close();
} catch (IOException ioe){
ioe.printStackTrace();
}
}
}
}

class TxtFileFilter extends FileFilter{

@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}

@Override
public String getDescription() {
return "*.txt(文本文件)";
}

}

class FontDialog extends JDialog{
private JComboBox cb_FontSize;
private JComboBox cb_FontStyle;
private JComboBox cb_FontNm;
private Font font;
Hashtable<Integer, String> style = new Hashtable<Integer, String>();

public FontDialog(){
this(null, null);
}

public FontDialog(Frame owner, Font font){
super(owner);
this.font = font == null?getFont():font;
setTitle("字體選擇框");
setModal(true);
setResizable(false);
setSize(326, 164);
getContentPane().setLayout(null);

final JLabel lb_FontNm = new JLabel();
lb_FontNm.setText("字體名稱");
lb_FontNm.setBounds(10, 10, 66, 16);
getContentPane().add(lb_FontNm);

cb_FontNm = new JComboBox();
cb_FontNm.setBounds(10, 28, 133, 25);
getContentPane().add(cb_FontNm);

cb_FontStyle = new JComboBox();
cb_FontStyle.setBounds(169, 28, 66, 25);
getContentPane().add(cb_FontStyle);

cb_FontSize = new JComboBox();
cb_FontSize.setBounds(258, 28, 53, 25);
getContentPane().add(cb_FontSize);

final JButton btn_OK = new JButton();
btn_OK.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
int styleCode = 0;
for(Enumeration<Integer> i = style.keys();i.hasMoreElements();){
styleCode = i.nextElement();
if(style.get(styleCode).equals(cb_FontStyle.getSelectedItem()))
break;
}
Font font = new Font(cb_FontNm.getSelectedItem().toString(), styleCode, ((Integer)cb_FontSize.getSelectedItem()).intValue());
setSelectedFont(font);
dispose();
}
});
btn_OK.setText("確定");
btn_OK.setBounds(58, 83, 76, 26);
getContentPane().add(btn_OK);

final JButton btn_Cancel = new JButton();
btn_Cancel.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
dispose();
}
});
btn_Cancel.setText("取消");
btn_Cancel.setBounds(169, 83, 76, 26);
getContentPane().add(btn_Cancel);

final JLabel lb_FontStyle = new JLabel();
lb_FontStyle.setText("字體樣式");
lb_FontStyle.setBounds(169, 10, 66, 16);
getContentPane().add(lb_FontStyle);

final JLabel lb_FontSize = new JLabel();
lb_FontSize.setText("字體大小");
lb_FontSize.setBounds(258, 10, 66, 16);
getContentPane().add(lb_FontSize);

init();
setVisible(true);
}

private void init(){
GraphicsEnvironment gg=GraphicsEnvironment.getLocalGraphicsEnvironment();
String ss[]=gg.getAvailableFontFamilyNames();
for(String s : ss)
cb_FontNm.addItem(s);
if(font != null)
cb_FontNm.setSelectedItem(font.getFamily());

style.put(Font.PLAIN, "標准");
style.put(Font.BOLD, "粗體");
style.put(Font.ITALIC, "斜體");
style.put(Font.BOLD+Font.ITALIC, "粗體&斜體");

cb_FontStyle.addItem(style.get(Font.PLAIN));
cb_FontStyle.addItem(style.get(Font.BOLD));
cb_FontStyle.addItem(style.get(Font.ITALIC));
cb_FontStyle.addItem(style.get(Font.BOLD+Font.ITALIC));

if(font != null)
cb_FontStyle.setSelectedItem(style.get(font.getStyle()));

for(int i=8;i<23;i++)
cb_FontSize.addItem(i);
if(font != null)
cb_FontSize.setSelectedItem(font.getSize());

}

public Font getSelectedFont() {
return font;
}

public void setSelectedFont(Font font) {
this.font = font;
}
}

class AboutDialog extends JDialog{
public AboutDialog(JFrame owner){
super(owner);
setTitle("關於");
setSize(new Dimension(322, 163));
getContentPane().setLayout(null);

final JLabel version = new JLabel();
version.setText("MyText 1.0");
version.setBounds(74, 37, 66, 16);
getContentPane().add(version);

final JLabel right = new JLabel();
right.setText("Copyright (C) 2010");
right.setBounds(74, 59, 188, 16);
getContentPane().add(right);

final JSeparator separator = new JSeparator();
separator.setBounds(70, 90, 210, 2);
getContentPane().add(separator);

final JButton okButton = new JButton();
okButton.setBounds(235, 95, 50, 26);
getContentPane().add(okButton);
okButton.setText("Ok");
okButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
dispose();
}
});
}
}
}

閱讀全文

與java設計記事本相關的資料

熱點內容
newfile命令快捷鍵 瀏覽:567
阿里雲物理伺服器 瀏覽:953
靈狐視頻app哪個好 瀏覽:257
大廠退役程序員自述 瀏覽:252
linux命令watch 瀏覽:889
加密幣哪些平台不撤出中國 瀏覽:553
max加線命令 瀏覽:424
app胖瘦模式哪個好用 瀏覽:724
可以下載源碼的軟體 瀏覽:487
程序員寫一天代碼累嗎 瀏覽:628
ie文件夾禁止訪問 瀏覽:544
百川互聯網程序員 瀏覽:784
linuxpython解釋器 瀏覽:669
興安得力軟體加密狗 瀏覽:494
智能網路攝像頭加密 瀏覽:574
軟體畢業程序員培訓 瀏覽:654
安卓陀螺儀低怎麼辦 瀏覽:248
一級建造師復習題集pdf 瀏覽:904
法理學pdf海默 瀏覽:394
伺服器內存儲器是用什麼的 瀏覽:820