文本編輯器源碼
『壹』 誰有javaScript寫的文本編輯器源碼像百度空間里的那種
文本編輯器。。
<input type=text...不就可以編輯么
-----------------------------------------------------
<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>新建網頁 1</title>
</head>
<body onload="setStart()" bgcolor=#C0C0C0>
<script language=javascript>
function ziti(){
form1.S1.style.fontFamily=form1.choose2.value;
}
function zihao(){ //字的顏色,在S1的的文本里
form1.S1.style.fontSize=form1.choose4.value;
}
function zicolor(){ //字的顏色 在S1的的文本里
form1.S1.style.color=form1.choose3.value;
}
function xieti(){ //設置斜體字 在S1的的文本里 fontstyle是斜體的屬性類
if(form1.S1.style.fontStyle=="italic") //斜體的單詞是italic
form1.S1.style.fontStyle="Normal";
else
form1.S1.style.fontStyle="Italic";
}
function cuti(){ //設置粗體字 在S1的的文本里 fontweight是粗提的屬性類
if(form1.S1.style.fontWeight=="bold") //斜體的單詞是bold
form1.S1.style.fontWeight="Normal";
else
form1.S1.style.fontWeight="Bold";
}
function xiaxian(){
//alert(form1.S1.style.textDecoration);
if(form1.S1.style.textDecoration=="underline") //斜體的單詞是bold
form1.S1.style.textDecoration="None";
else
form1.S1.style.textDecoration="underline";
}
function AddTextArea(){
var a=document.createElement("textarea");
a.style.width=400;
a.style.height=200;
a.innerText=form1.S1.value
a.style.fontFamily=form1.choose2.value
a.style.fontSize=form1.choose4.value
a.style.color=form1.choose3.value
f2.appendChild(a);
for(i=0;i<4;i++){
var a=document.createElement("br");
f2.appendChild(a);}
}
function setStart(){
form1.S1.style.width=400;
form1.S1.style.height=200;
}
function Beijing(){
form1.S1.style.backgroundColor=form1.choose1.value;
}
</script>
<table bgcolor=#666666 border="1" width="100%" id="table2">
<tr>
<td><font face="黑體" size="2" color="#800080"><marquee>Vaux論壇</marquee></font></td>
</tr>
</table>
<table border="1" width="100%" id="table3">
<tr>
<td>日期:</td>
</tr>
</table>
<table border="0" width="100%" id="table1" height="586" cellspacing="0" cellpadding="0" >
<form name=form1 method =get >
<tr>
<td height="33"><font face="華文行楷" size="4">【姓名】:</font></td>
<td height="33">論題:</td>
</tr>
<tr>
<td><font face="華文行楷" size="4">【ID】:</font></td>
<td><input type="text" name="T1" size="65"></td>
</tr>
<tr>
<td rowspan="3" width="29%">
<img border="0" src="1.jpg" width="276" height="277"></td>
<td height="71" width="71%">
<p align=center>
背景<select size="1" name="choose1" onchange=Beijing()>
<option selected value="yellow">清風</option>
<option value="white">血白</option>
<option value="red">火紅</option>
<option value="green">油綠</option>
</select>字體<select size="1" name="choose2" onchange=ziti()>
<option selected value="宋體">宋體</option>
<option value="黑體">黑體</option>
<option value="隸書">隸書</option>
</select>顏色<select size="1" name="choose3" onchange=zicolor()>
<option selected value="black">黑</option>
<option value="red">紅</option>
<option value="yellow">黃</option>
<option value="green">綠</option>
</select>字型大小<select size="1" name="choose4" onchange=zihao();>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
<input type="button" value="I" name="b3" onclick="xieti()">
<input type="button" value="B" name="b4" onclick="cuti()">
<input type="button" value="_" name="b5" onclick="xiaxian()"></p>
</td>
</tr>
<tr>
<td height="270" width="71%"><textarea rows="12" name="S1" cols="71" ></textarea></td>
</tr>
<tr>
<td height="26" width="71%">
<p align=right>
<input type="button" value="提交" name="b1" style="float: right" onclick=AddTextArea()><input type="reset" value="重置" name="b2"></p>
</td>
</tr>
</table>
</form>
<hr>
<center>
<form method="POST" action="_derived/nortbots.htm" name=f2 onSubmit="location.href='_derived/nortbots.htm';return false;" webbot-onSubmit webbot-action="--WEBBOT-SELF--" >
</form>
</center>
<hr>
</body>
</html>
『貳』 java語言寫一個文本編輯器的源代碼
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.*; //Date needed
import java.io.PrintWriter;
public class NotePad extends JFrame
{
JTextArea jta;
class newl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.setText("");
}
}
class openl implements ActionListener
{ public void actionPerformed(ActionEvent e)
{
JFileChooser jf=new JFileChooser();
jf.showOpenDialog(NotePad.this);
}
}
//保存文件的監聽
class savel implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser jf = new JFileChooser();
jf.showSaveDialog(NotePad.this);
}
}
//列印的監聽 ?
class printl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// PrintWriter p = new PrintWriter(NotePad.this);
}
}
//退出記事本的監聽
class exitl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);//退出
}
}
//拷貝的監聽
class l implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.();
}
}
//粘貼的監聽
class pastel implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.paste();
}
}
//剪切的監聽
class cutl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.cut();
}
}
//查找的監聽
//添加日期的監聽
class datel implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Date d=new Date();
jta.append(d.toString());
}
}
//構造函數
public NotePad()
{
jta=new JTextArea("",24,40);
JScrollPane jsp=new JScrollPane(jta);
JMenuBar jmb=new JMenuBar();
JMenu mFile=new JMenu("File");
JMenu mEdit=new JMenu("Edit");
JMenuItem mNew=new JMenuItem("New",KeyEvent.VK_N);
mNew.addActionListener(new newl());
mFile.add(mNew);
JMenuItem mOpen=new JMenuItem("Open",KeyEvent.VK_O);
mOpen.addActionListener(new openl());
mFile.add(mOpen);
JMenuItem mSave=new JMenuItem("Save");
mSave.addActionListener(new savel());
mFile.add(mSave);
mFile.addSeparator(); //添加分割線
JMenuItem mPrint = new JMenuItem("Print");
mPrint.addActionListener(new printl());
mFile.add(mPrint);
mFile.addSeparator(); //添加分割線
JMenuItem mExit=new JMenuItem("Exit");
mExit.addActionListener(new exitl());
mFile.add(mExit);
mFile.setMnemonic(KeyEvent.VK_F);
//編輯菜單的子菜單的處理
JMenuItem jmi;
jmi=new JMenuItem("Copy");
jmi.addActionListener(new l());
mEdit.add(jmi);
jmi=new JMenuItem("Cut");
jmi.addActionListener(new cutl());
mEdit.add(jmi);
jmi=new JMenuItem("Paste");
jmi.addActionListener(new pastel());
mEdit.add(jmi);
mEdit.addSeparator(); //添加分割線
jmi=new JMenuItem("Find");
mEdit.add(jmi);
jmi=new JMenuItem("FindNext");
mEdit.add(jmi);
mEdit.addSeparator();
jmi=new JMenuItem("Select All");
mEdit.add(jmi);
jmi=new JMenuItem("Date/Time");
jmi.addActionListener(new datel());
mEdit.add(jmi);
jmb.add(mFile);
jmb.add(mEdit);
this.setJMenuBar(jmb);
this.getContentPane().add(jsp);
this.setSize(200,200);
this.setVisible(true);
}
//主函數,程序入口點
public static void main(String s[])
{
new NotePad();
}
}
『叄』 用匯編語言設計一個「簡單的文本編輯器」
說明: 雙擊可執行文件wbbjq.exe,在出現的界面中輸入任意文本內容,利用DEL鍵、
BACKSPACE鍵、HOME鍵、END鍵、上下左右游標鍵對文本進行全屏幕編輯,
按f1鍵激活菜單file,下移游標,選納空者洞薯擇save,輸入文件名。也可以選擇FILE菜單
的其他菜單項,他們虧李的功能均可實現。按f10激活幫助,按ESC鍵退出幫助。
源程序:
red_chr macro ;讀取字元宏定義
mov ah,0
int 16h
endm
string macro p1 ;輸入字元游標
mov ah,9
lea dx,p1
int 21h
endm
win macro opr1,opr2,opr3,opr4,opr5,opr6 ;建立窗口
mov ah,06h
mov al,opr1
mov bh,opr2
mov ch,opr3
mov cl,opr4
mov dh,opr5
mov dl,opr6
int 10h
endm
pos_curse macro op1,op2,op3 ;定義游標位置
mov ah,2
mov bh,op1
mov dh,op2
mov dl,op3
int 10h
endm
pos_get macro ;顯示游標位置
mov ah,03h
mov bh,0
int 10h
endm
data segment ;定義數據段
menu db 'File Edit Help $'
mass_1 db 'F1 Active file F10 Active help','$'
manu_1 db ' New ',13,10,'$'
manu_2 db ' Open ',13,10,'$'
manu_3 db ' Save ',13,10,'$'
manu_4 db ' Save as ',13,10,'$'
manu_5 db ' Exit ','$'
handle dw ?
message1 db ' Please input file name:','$'
message2 db ' Please input save file name:','$'
message3 db ' Please input open file name:','$'
message4 db ' ***The file is not save! Save it now? (Y/N)***: ','$'
path db 50 p(0),'$'
buffer db 2000 p(?)
bak db 3850 p(0)
line db ?
row db ?
char db ?
help_mas1 db ' welcome use editor! $' ;幫助內容
help_mas2 db 'please the first active help! $'
help_mas3 db 'good lucky!! $'
help_mas4 db '==========================================================$'
help_mas5 db 'Press F1 to active file. $'
help_mas6 db 'You can use DOWN cursor key to choose the fuction $'
help_mas7 db 'Press F10 to show the help massage.Press Esc To Quit$'
date db 'today ??/??/','$' ;調用日期
hanglie db '???//???','$' ;行//列
data ends
code segment
main proc far ;主程序
assume cs:code,ds:data
start:
push ds
sub ax,ax
push ax
mov ax,data
mov ds,ax
call wind
call edit
ret
main endp
wind proc near ;創建窗口子程序
win 0,3eh,1,0,24,79 ;定義窗口背景
win 1,1fh,0,0,0,79
win 0,1fh,24,0,24,79
show: ;顯示菜單位置及內容
pos_curse 0,0,1
mov ah,9
lea dx,menu
int 21h
show_2: ;顯示狀態欄位置及內容
pos_curse 0,24,1
mov ah,9
lea dx,mass_1
int 21h
call win3
call win4
pos_curse 0,1,0
mov row,dh
mov line,dl
wind endp
edit proc near
char_get: ;讀字元
call com
com proc near ;定義功能鍵
pos_get
mov row,dh
mov line,dl
first:
pos_curse 0,row,line
j00: mov ah,0
int 16h ;從鍵盤讀字元 ah=掃描碼 al=字元碼
push ax
lea dx,buffer
mov buffer[bx],al
inc bx
cmp ah,48h ;上
jz up_1
cmp ah,50h ;下
jz down_1
cmp ah,4bh ;左
jz left
cmp ah,4dh ;右
jz right
cmp ah,1ch ;回車
jz enter_1
call fuc_key
mov ah,2
mov dl,al
int 21h
pop ax
call menu_show
jmp j6
down_1:
jmp down
enter_1:
jmp enter_2
up_1: jmp up
left: ;游標左移
pos_get
mov row,dh
mov dl,line
cmp line,0
jnz direct
mov line,79
dec row
cmp row,0
je stop2
jmp first
stop2:
mov row,1
jmp first
direct:
dec line
call win4 ;顯示游標位置
jmp first
right: ;游標右移
pos_get
mov row,dh
mov dl,line
cmp line,79
jnz direct2
mov line,0
inc row
cmp row,24
je returns1
jmp first
direct2:
inc line
call win4
jmp first
enter_2:
jmp enter
up: ;上移游標
pos_get
mov row,dh
mov dl,line
dec row
cmp row,0
je stop1
call win4
jmp first
stop1:
mov row,1
jmp first
down: ;下移游標
pos_get
mov row,dh
mov dl,line
inc row
cmp row,24
je stop3
call win4
jmp first
stop3:
mov row,23
jmp first
returns1:
jmp returns
enter: ;回車換行
pos_get
mov row,dh
mov line,dl
inc row
cmp row,24
je returns
mov line,0
call win4
jmp first
returns:
mov row,24
mov line,0
jmp first
j6:
ret
com endp
fuc_key proc near ;功能鍵子程序
next:
cmp ah,47h ;home
jz home
cmp ah,4fh ;end
jz _end
cmp ah,0eh ;backspace
jz bak_sp
cmp ah,53h
jz del
cmp ah,44h ;F10
jz help_0
ret
help_0: call help
home: ;HOME鍵的功能
pos_get
mov row,dh
mov line,0
call win4
jmp first
_end: ;END鍵的功能
pos_get
mov row,dh
mov line,79
call win4
jmp first
bak_sp: ;退格鍵的功能
pos_get
mov row,dh
mov line,dl
cmp line,0
je stop
dec line
jmp ab
stop:
mov line,0
ab:
pos_get 0,row,line
mov ah,2
mov dl,00
int 21h
call win4
jmp first
del: ;DEL刪除
pos_get
mov row,dh
mov line,dl
dec line
pos_get 0,row,line
mov ah,2
mov dl,00
int 21h
inc line
call win4
jmp first
cm:
cmp line,00
jz pos_cm
pos_cm:
pos_curse 0,0,0
jmp first
help proc near ;顯示幫助信息
call savedisplay ;顯示幫助信息每行的位置
pos_get
push dx
win 0,57h,4,5,21,70
pos_curse 0,6,25
string help_mas1
pos_curse 0,8,11
string help_mas2
pos_curse 0,10,11
string help_mas3
pos_curse 0,12,11
string help_mas4
pos_curse 0,14,11
string help_mas5
pos_curse 0,16,11
string help_mas6
pos_curse 0,18,11
string help_mas7
pop dx
pos_curse 0,dh,dl
mov ah,0
int 16h
cmp ah,36h ;F10 active help
jnz cls
call help
cls:
win 0,1eh,9,10,13,70 ;清屏
call backdisplay
help endp
fuc_key endp
menu_show proc near ;顯示菜單
call savedisplay
push cx
cmp ah,3bh ;F1功能
jz menu_sh
jmp char_get
menu_sh: ;定義菜單的背景字體顏色
pos_get
push dx
win 0,06h,2,1,7,11
win 0,65h,1,0,6,10
pos_curse 0,1,0
string manu_1
string manu_2
string manu_3
string manu_4
string manu_5
pop dx
dec dl
pos_curse 0,dh,dl
copmar:
red_chr
cmp ah,50h
jz manu_n
jmp manu_hid
manu_hid: ;菜單隱藏
win 0,1eh,1,1,7,11
call backdisplay
jmp char_get
manu_n: ;開始定義各個菜單項
win 0,65h,5,1,5,8
pos_curse 0,5,0
string manu_5
win 0,15h,1,1,1,8
pos_curse 0,1,0
string manu_1
red_chr
cmp ah,48h
je manu_n
cmp al,0dh
jz new_1
cmp ah,50h
je manu_o
jmp manu_hid
manu_n0:
jmp manu_n
manu_o:
win 0,65h,1,1,1,8
pos_curse 0,1,0
string manu_1
win 0,15h,2,1,2,8
pos_curse 0,2,0
string manu_2
red_chr
cmp ah,48h
je manu_o
cmp al,0dh
jz open_1
cmp ah,50h
je manu_s
jmp manu_hid
new_1: jmp new_2
manu_s:
win 0,65h,2,1,2,8
pos_curse 0,2,0
string manu_2
win 0,15h,3,1,3,8
pos_curse 0,3,0
string manu_3
red_chr
cmp al,0dh
jz save_1
cmp ah,48h
je manu_s
cmp ah,50h
je manu_a
jmp manu_hid
open_1: jmp open_2
manu_n1:
jmp manu_n
manu_a:
win 0,65h,3,1,3,8
pos_curse 0,3,0
string manu_3
win 0,15h,4,1,4,8
pos_curse 0,4,0
string manu_4
red_chr
cmp ah,1ch
jz save_2
cmp ah,48h
je manu_a
cmp ah,50h
je manu_e
jmp manu_hid
manu_n2:
jmp manu_n1
new_2: jmp new
save_1: call save
save_2: call saveas
manu_e:
win 0,65h,4,1,4,8
pos_curse 0,4,0
string manu_4
win 0,15h,5,1,5,8
pos_curse 0,5,0
string manu_5
red_chr
cmp ah,50h
je manu_n2
cmp ah,48h
je manu_e
cmp ah,1ch
je exit
jmp manu_hid
exit:
call backdisplay
win 0,07h,15,10,17,61
win 0,24h,14,9,16,60
mov dh,15
mov dl,9
mov bh,0
mov ah,2
int 10h
lea dx,message4
mov ah,9
int 21h
mov ah,1
int 21h
cmp al,79h
jnz q
call quitt
q: cmp al,6eh
jz quit
quit: win 0,07h,0,0,24,79
pos_curse 0,0,0
mov ah,4ch
int 21h
ret
menu_show endp
new proc near ;新建文件
pos_get
push dx
call backdisplay
win 0,07h,15,10,17,61
win 0,24h,14,9,16,60,
mov dh,15
mov dl,9
mov bh,0
mov ah,2
int 10h
lea dx,message1
cmp al,0dh
mov ah,9
int 21h
mov bx,0
all:
mov ah,1
int 21h
cmp al,0dh
je alll
mov path[bx],al
inc bx
jmp all
alll:
win 0,3eh,15,9,17,61
pop dx
pos_curse 0,dh,dl
lea dx,path
mov ah,3ch
mov cx,00
int 21h
mov handle,ax
mov bx,ax
mov ah,3eh
int 21h
win 0,3eh,1,0,23,79
mov dh,1
mov dl,0
mov bh,0
mov ah,2
int 10h
jmp char_get
new endp
open_2: jmp open
saveas proc near ;另存為文件 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
win 0,3eh,1,0,6,10
call backdisplay
win 0,07h,15,10,17,61
win 0,24h,14,9,16,60,
mov dh,15
mov dl,9
mov bh,0
mov ah,2
int 10h
lea dx,message2
mov ah,9
int 21h
mov bx,0
bll:
mov ah,1
int 21h
cmp al,0dh
je blll
mov path[bx],al
inc bx
jmp bll
blll:
pos_get
push dx
win 0,3eh,1,0,23,79
call backdisplay
pop dx
pos_curse 0,dh,dl
lea dx,path
mov ah,3ch
mov cx,00
int 21h
mov handle,ax
lea dx,buffer
mov bx,handle
mov cx,2000
mov ah,40h
int 21h
mov bx,handle
mov ah,3eh
int 21h
call backdisplay
jmp char_get
saveas endp
open proc near ;打開文件
call backdisplay
win 0,07h,15,10,17,61
win 0,24h,14,9,16,60
mov dh,15
mov dl,9
mov bh,0
mov ah,2
int 10h
lea dx,message3
mov ah,9
int 21h
mov bx,0
cll:
mov ah,1
int 21h
cmp al,13
je clll
mov path[bx],al
inc bx
jmp cll
clll:
win 0,3eh,1,0,23,79
lea dx,path
mov ah,3dh
mov al,0
int 21h
mov handle,ax
lea dx,buffer
mov bx,handle
mov cx,2000
mov ah,3fh
int 21h
win 0,3eh,1,23,1,79
mov dh,1
mov dl,0
mov bh,0
mov ah,2
int 10h
mov cx,1000
sub bx,bx
replay:
mov dl,buffer[bx]
inc bx
mov ah,2
int 21h
loop replay
mov bx,handle
mov ah,3eh
int 21h
mov dh,1
mov dl,0
mov bh,0
mov ah,2
int 10h
mov cx,10
mov bx,0
cleapath_3:
mov bl,0
mov path[bx],bl
loop cleapath_3
jmp char_get
open endp
save proc near ;保存文件
pos_get
push dx
win 0,3eh,1,0,6,10
call backdisplay
mov ah,path
cmp ah,21h
jl j_3
jmp j_4
j_3:
win 0,07h,15,10,17,61
win 0,24h,14,9,16,60,
mov dh,15
mov dl,9
mov bh,0
mov ah,2
int 10h
lea dx,message2
mov ah,9
int 21h
mov bx,0
dll:
mov ah,1
int 21h
cmp al,0dh
je dlll
mov path[bx],al
inc bx
jmp dll
dlll:
win 0,3eh,1,0,23,79
pop dx
pos_curse 0,dh,dl
j_4: lea dx,path
mov ah,3ch
mov cx,00
int 21h
mov handle,ax
lea dx,buffer
mov bx,handle
mov cx,2000
mov ah,40h
int 21h
mov bx,handle
mov ah,3eh
int 21h
call backdisplay
jmp char_get
save endp
savedisplay proc near
push ax
push bx
push cx
push dx
push ds
mov ax,0002h
int 33h
mov bx,0d
mov cx,3840d
loop1:
mov ax,0b800h
mov ds,ax
mov dl,ds:[bx]
mov ax,data
mov ds,ax
mov bak[bx],dl
inc bx
loop loop1
mov ax,0001h
int 33h
pop ds
pop dx
pop cx
pop bx
pop ax
savedisplay endp
backdisplay proc near
push ax
push bx
push cx
push dx
push ds
mov bx,0d
mov cx,3840d
loop11:
mov ax,data
mov ds,ax
mov dl,bak[bx]
mov ax,0b800h
mov ds,ax
mov ds:[bx],dl
inc bx
loop loop11
pop ds
pop dx
pop cx
pop bx
pop ax
ret
backdisplay endp
quitt proc near ;退出
call backdisplay
win 0,07h,15,10,17,61
win 0,24h,14,9,16,60,
mov dh,15
mov dl,9
mov bh,0
mov ah,2
int 10h
lea dx,message2
mov ah,9
int 21h
mov bx,0
qll:
mov ah,1
int 21h
cmp al,0dh
je qlll
mov path[bx],al
inc bx
jmp qll
qlll:
win 0,07h,15,10,17,61
win 0,3eh,14,9,16,60
call backdisplay
lea dx,path
mov ah,3ch
mov cx,00
int 21h
mov handle,ax
lea dx,buffer
mov bx,handle
mov cx,2000
mov ah,40h
int 21h
mov bx,handle
mov ah,3eh
int 21h
call backdisplay
win 0,07h,0,0,24,79
mov ah,4ch
int 21h
ret
quitt endp
edit endp
win3 proc near ;顯示日期
mov ah,2ah
int 21h
mov bl,10d
mov ax,0
mov al,dh
div bl
add ax,3030h
mov [date+6],al
mov [date+7],ah
mov ax,0
mov al,dl
div bl
add ax,3030h
mov [date+9],al
mov [date+10],ah
win 0,1dh,0,67,0,79
pos_curse 0,0,67
mov dx,offset date
mov ah,09h
int 21h
ret
win3 endp
win4 proc near ;顯示行//列
mov ah,03h
mov bh,0
int 10h
mov bl,100d
mov bh,10d
mov ax,0
mov al,dh
div bl
add al,30h
mov [hanglie+0],al
mov al,ah
mov ah,0
div bh
add ax,3030h
mov [hanglie+1],al
mov [hanglie+2],ah
mov ax,0
mov al,dl
div bl
add al,30h
mov [hanglie+5],al
mov al,ah
mov ah,0
div bh
add ax,3030h
mov [hanglie+6],al
mov [hanglie+7],ah
win 0,1dh,24,60,24,70
pos_curse 0,24,61
mov dx,offset hanglie
mov ah,09h
int 21h
ret
win4 endp
code ends
end start ;結束
『肆』 java語言寫一個文本編輯器的源代碼 要能測試通過的!用Eclipse能運行通過的!
一. 高亮的內容:
需要高亮的內容有:
1. 關鍵字, 如 public, int, true 等.
2. 運算符, 如 +, -, *, /等
3. 數字
4. 高亮字元串, 如 "example of string"
5. 高亮單行注釋
6. 高亮多行注釋
二. 實現高亮的核心方法:
StyledDocument.setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace)
三. 文本編輯器選擇.
Java中提供的多行文本編輯器有: JTextComponent, JTextArea, JTextPane, JEditorPane等, 都可以使用. 但是因為語法著色中文本要使用多種風格的樣式, 所以這些文本編輯器的document要使用StyledDocument.
JTextArea使用的是PlainDocument, 此document不能進行多種格式的著色.
JTextPane, JEditorPane使用的是StyledDocument, 默認就可以使用.
為了實現語法著色, 可以繼承自DefaultStyledDocument, 設置其為這些文本編輯器的documet, 或者也可以直接使用JTextPane, JEditorPane來做. 為了方便, 這里就直接使用JTextPane了.
四. 何時進行著色.
當文本編輯器中有字元被插入或者刪除時, 文本的內容就發生了變化, 這時檢查, 進行著色.
為了監視到文本的內容發生了變化, 要給document添加一個DocumentListener監聽器, 在他的removeUpdate和insertUpdate中進行著色處理.
而changedUpdate方法在文本的屬性例如前景色, 背景色, 字體等風格改變時才會被調用.
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
try {
colouring((StyledDocument) e.getDocument(), e.getOffset(), e.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
@Override
public void removeUpdate(DocumentEvent e) {
try {
// 因為刪除後游標緊接著影響的單詞兩邊, 所以長度就不需要了
colouring((StyledDocument) e.getDocument(), e.getOffset(), 0);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
五. 著色范圍:
pos: 指變化前游標的位置.
len: 指變化的字元數.
例如有關鍵字public, int
單詞"publicint", 在"public"和"int"中插入一個空格後變成"public int", 一個單詞變成了兩個, 這時對"public" 和 "int"進行著色.
著色范圍是public中p的位置和int中t的位置加1, 即是pos前面單詞開始的下標和pos+len開始單詞結束的下標. 所以上例中要著色的范圍是"public int".
提供了方法indexOfWordStart來取得pos前單詞開始的下標, 方法indexOfWordEnd來取得pos後單詞結束的下標.
public int indexOfWordStart(Document doc, int pos) throws BadLocationException {
// 從pos開始向前找到第一個非單詞字元.
for (; pos > 0 && isWordCharacter(doc, pos - 1); --pos);
return pos;
}
public int indexOfWordEnd(Document doc, int pos) throws BadLocationException {
// 從pos開始向前找到第一個非單詞字元.
for (; isWordCharacter(doc, pos); ++pos);
return pos;
}
一個字元是單詞的有效字元: 是字母, 數字, 下劃線.
public boolean isWordCharacter(Document doc, int pos) throws BadLocationException {
char ch = getCharAt(doc, pos); // 取得在文檔中pos位置處的字元
if (Character.isLetter(ch) || Character.isDigit(ch) || ch == '_')
return false;
}
所以著色的范圍是[start, end] :
int start = indexOfWordStart(doc, pos);
int end = indexOfWordEnd(doc, pos + len);
六. 關鍵字著色.
從著色范圍的開始下標起進行判斷, 如果是以字母開或者下劃線開頭, 則說明是單詞, 那麼先取得這個單詞, 如果這個單詞是關鍵字, 就進行關鍵字著色, 如果不是, 就進行普通的著色. 著色完這個單詞後, 繼續後面的著色處理. 已經著色過的字元, 就不再進行著色了.
public void colouring(StyledDocument doc, int pos, int len) throws BadLocationException {
// 取得插入或者刪除後影響到的單詞.
// 例如"public"在b後插入一個空格, 就變成了:"pub lic", 這時就有兩個單詞要處理:"pub"和"lic"
// 這時要取得的范圍是pub中p前面的位置和lic中c後面的位置
int start = indexOfWordStart(doc, pos);
int end = indexOfWordEnd(doc, pos + len);
char ch;
while (start < end) {
ch = getCharAt(doc, start);
if (Character.isLetter(ch) || ch == '_') {
// 如果是以字母或者下劃線開頭, 說明是單詞
// pos為處理後的最後一個下標
start = colouringWord(doc, start);
} else {
//SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, normalStyle));
++start;
}
}
}
public int colouringWord(StyledDocument doc, int pos) throws BadLocationException {
int wordEnd = indexOfWordEnd(doc, pos);
String word = doc.getText(pos, wordEnd - pos); // 要進行著色的單詞
if (keywords.contains(word)) {
// 如果是關鍵字, 就進行關鍵字的著色, 否則使用普通的著色.
// 這里有一點要注意, 在insertUpdate和removeUpdate的方法調用的過程中, 不能修改doc的屬性.
// 但我們又要達到能夠修改doc的屬性, 所以把此任務放到這個方法的外面去執行.
// 實現這一目的, 可以使用新線程, 但放到swing的事件隊列里去處理更輕便一點.
SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, keywordStyle));
} else {
SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, normalStyle));
}
return wordEnd;
}
因為在insertUpdate和removeUpdate方法中不能修改document的屬性, 所以著色的任務放到這兩個方法外面, 所以使用了SwingUtilities.invokeLater來實現.
private class ColouringTask implements Runnable {
private StyledDocument doc;
private Style style;
private int pos;
private int len;
public ColouringTask(StyledDocument doc, int pos, int len, Style style) {
this.doc = doc;
this.pos = pos;
this.len = len;
this.style = style;
}
public void run() {
try {
// 這里就是對字元進行著色
doc.setCharacterAttributes(pos, len, style, true);
} catch (Exception e) {}
}
}
七: 源碼
關鍵字著色的完成代碼如下, 可以直接編譯運行. 對於數字, 運算符, 字元串等的著色處理在以後的教程中會繼續進行詳解.
import java.awt.Color;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class HighlightKeywordsDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JTextPane editor = new JTextPane();
editor.getDocument().addDocumentListener(new SyntaxHighlighter(editor));
frame.getContentPane().add(editor);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
/**
* 當文本輸入區的有字元插入或者刪除時, 進行高亮.
*
* 要進行語法高亮, 文本輸入組件的document要是styled document才行. 所以不要用JTextArea. 可以使用JTextPane.
*
* @author Biao
*
*/
class SyntaxHighlighter implements DocumentListener {
private Set<String> keywords;
private Style keywordStyle;
private Style normalStyle;
public SyntaxHighlighter(JTextPane editor) {
// 准備著色使用的樣式
keywordStyle = ((StyledDocument) editor.getDocument()).addStyle("Keyword_Style", null);
normalStyle = ((StyledDocument) editor.getDocument()).addStyle("Keyword_Style", null);
StyleConstants.setForeground(keywordStyle, Color.RED);
StyleConstants.setForeground(normalStyle, Color.BLACK);
// 准備關鍵字
keywords = new HashSet<String>();
keywords.add("public");
keywords.add("protected");
keywords.add("private");
keywords.add("_int9");
keywords.add("float");
keywords.add("double");
}
public void colouring(StyledDocument doc, int pos, int len) throws BadLocationException {
// 取得插入或者刪除後影響到的單詞.
// 例如"public"在b後插入一個空格, 就變成了:"pub lic", 這時就有兩個單詞要處理:"pub"和"lic"
// 這時要取得的范圍是pub中p前面的位置和lic中c後面的位置
int start = indexOfWordStart(doc, pos);
int end = indexOfWordEnd(doc, pos + len);
char ch;
while (start < end) {
ch = getCharAt(doc, start);
if (Character.isLetter(ch) || ch == '_') {
// 如果是以字母或者下劃線開頭, 說明是單詞
// pos為處理後的最後一個下標
start = colouringWord(doc, start);
} else {
SwingUtilities.invokeLater(new ColouringTask(doc, start, 1, normalStyle));
++start;
}
}
}
/**
* 對單詞進行著色, 並返回單詞結束的下標.
*
* @param doc
* @param pos
* @return
* @throws BadLocationException
*/
public int colouringWord(StyledDocument doc, int pos) throws BadLocationException {
int wordEnd = indexOfWordEnd(doc, pos);
String word = doc.getText(pos, wordEnd - pos);
if (keywords.contains(word)) {
// 如果是關鍵字, 就進行關鍵字的著色, 否則使用普通的著色.
// 這里有一點要注意, 在insertUpdate和removeUpdate的方法調用的過程中, 不能修改doc的屬性.
// 但我們又要達到能夠修改doc的屬性, 所以把此任務放到這個方法的外面去執行.
// 實現這一目的, 可以使用新線程, 但放到swing的事件隊列里去處理更輕便一點.
SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, keywordStyle));
} else {
SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, normalStyle));
}
return wordEnd;
}
/**
* 取得在文檔中下標在pos處的字元.
*
* 如果pos為doc.getLength(), 返回的是一個文檔的結束符, 不會拋出異常. 如果pos<0, 則會拋出異常.
* 所以pos的有效值是[0, doc.getLength()]
*
* @param doc
* @param pos
* @return
* @throws BadLocationException
*/
public char getCharAt(Document doc, int pos) throws BadLocationException {
return doc.getText(pos, 1).charAt(0);
}
/**
* 取得下標為pos時, 它所在的單詞開始的下標. ±wor^d± (^表示pos, ±表示開始或結束的下標)
*
* @param doc
* @param pos
* @return
* @throws BadLocationException
*/
public int indexOfWordStart(Document doc, int pos) throws BadLocationException {
// 從pos開始向前找到第一個非單詞字元.
for (; pos > 0 && isWordCharacter(doc, pos - 1); --pos);
return pos;
}
/**
* 取得下標為pos時, 它所在的單詞結束的下標. ±wor^d± (^表示pos, ±表示開始或結束的下標)
*
* @param doc
* @param pos
* @return
* @throws BadLocationException
*/
public int indexOfWordEnd(Document doc, int pos) throws BadLocationException {
// 從pos開始向前找到第一個非單詞字元.
for (; isWordCharacter(doc, pos); ++pos);
return pos;
}
/**
* 如果一個字元是字母, 數字, 下劃線, 則返回true.
*
* @param doc
* @param pos
* @return
* @throws BadLocationException
*/
public boolean isWordCharacter(Document doc, int pos) throws BadLocationException {
char ch = getCharAt(doc, pos);
if (Character.isLetter(ch) || Character.isDigit(ch) || ch == '_')
return false;
}
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
try {
colouring((StyledDocument) e.getDocument(), e.getOffset(), e.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
@Override
public void removeUpdate(DocumentEvent e) {
try {
// 因為刪除後游標緊接著影響的單詞兩邊, 所以長度就不需要了
colouring((StyledDocument) e.getDocument(), e.getOffset(), 0);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
/**
* 完成著色任務
*
* @author Biao
*
*/
private class ColouringTask implements Runnable {
private StyledDocument doc;
private Style style;
private int pos;
private int len;
public ColouringTask(StyledDocument doc, int pos, int len, Style style) {
this.doc = doc;
this.pos = pos;
this.len = len;
this.style = style;
}
public void run() {
try {
// 這里就是對字元進行著色
doc.setCharacterAttributes(pos, len, style, true);
} catch (Exception e) {}
}
}
}
『伍』 如何用java編寫一個簡單的文本編輯器
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class f1 extends Frame implements ActionListener
{
private MenuBar menubar=new MenuBar();
private Menu filemenu=new Menu("文件");
private Menu editmenu=new Menu("編輯");
private Menu formmenu=new Menu("格式");
private MenuItem[] itemf=new MenuItem[4];
private MenuItem[] iteme=new MenuItem[6];
private MenuItem[] items=new MenuItem[2];
private TextArea tf=new TextArea();
public int a=0,b=0,c=0,style=Font.PLAIN,size=15;
public String s1="red:"+a+" "+"green:"+b+" "+"blue"+c,
s2="宋體";
public String[] sz1={"10","16","24","30","32","36"},
sz2={"宋體","黑體","幼圓","隸書","行楷","Arial","Georgia"},
sz3={"粗體","傾斜","常規","粗斜"};
JDialog dialog=new JDialog(this,"字體",true);
Container cp=dialog.getContentPane();
JLabel[] lb=new JLabel[8];
JLabel lb1=new JLabel(s1,JLabel.LEFT);
JButton b1=new JButton("確定"),
b2=new JButton("取消");
JComboBox jc1=new JComboBox(),
jc2=new JComboBox(),
jc3=new JComboBox();
JScrollBar jb1=new JScrollBar(JScrollBar.HORIZONTAL,10,5,0,260);
JScrollBar jb2=new JScrollBar(JScrollBar.HORIZONTAL,10,5,0,260);
JScrollBar jb3=new JScrollBar(JScrollBar.HORIZONTAL,10,5,0,260);