欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

java實(shí)現(xiàn)編輯器的代碼 java實(shí)現(xiàn)編輯器的代碼是什么

求JAVA編寫的文本編輯器。

import java.awt.*;

獲嘉網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),獲嘉網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為獲嘉超過千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的獲嘉做網(wǎng)站的公司定做!

import java.awt.event.*;

import java.io.*;

public class Notepad /*implements ActionListener , MouseListener , MouseMotionListener , WindowListener , ItemListener , KeyListener, TextListener */

{

//成員變量

private Frame mainFrame;//主框架

private MenuBar mb ; //菜單條

private Menu mFile , mEdit , mFormat , mHelp ; //菜單:文件,編輯,格式,幫助

private MenuItem miNew , miOpen , miSave , miSaveAs , miExit ;//文件菜單項(xiàng):新建,打開,保存,另存為,退出

private MenuItem miCut , miCopy , miPaste , miDelete ;//編輯菜單項(xiàng):剪切,復(fù)制,粘貼,刪除

private MenuItem miFont , miLowtoCapital, miCapitaltoLow ,miEncrypt , miDisencrypt;//格式菜單項(xiàng):字體

private MenuItem miAboutNotepad;//幫助菜單項(xiàng):關(guān)于記事本

private TextArea ta;//文本區(qū)

private String tempString;//臨時(shí)字符串,用于存儲(chǔ)需要復(fù)制粘貼的字符串

private boolean textValueChanged = false;

private int id_font ;//字體

String fileName = "";//上次保存后的文件名和地址

//構(gòu)造函數(shù)

public Notepad(){

//框架

mainFrame = new Frame ("Notepad v0.99 by Launching");

mb = new MenuBar ();

ta = new TextArea (30 ,60);

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

ta.setBackground(new Color(0 , 250 , 200));

//菜單條

mFile = new Menu ( "File");

mEdit = new Menu ( "Edit");

mFormat = new Menu ("Format");

mHelp = new Menu ("Help");

//"文件"

miNew = new MenuItem ("New");

miOpen = new MenuItem ("Open");

miSave = new MenuItem ("Save");

miSaveAs = new MenuItem ("Save as");

miExit = new MenuItem ("Exit");

//"編輯"

miCut = new MenuItem ("Cut");

miCopy = new MenuItem ("Copy");

miPaste = new MenuItem ("Paste");

miDelete = new MenuItem ("Delete");

//"格式"

miFont = new MenuItem ("Font");

miLowtoCapital = new MenuItem("Low to Capital");

miCapitaltoLow = new MenuItem("Capital to Low");

miEncrypt = new MenuItem("Encrypt");

miDisencrypt = new MenuItem("Disencrypt");

//"幫助"

miAboutNotepad = new MenuItem ("About Notepad");

//添加文件菜單項(xiàng)

mFile.add(miNew);

mFile.add(miOpen);

mFile.add(miSave);

mFile.add(miSaveAs);

mFile.add(miExit);

//添加編輯菜單項(xiàng)

mEdit.add(miCut);

mEdit.add(miCopy);

mEdit.add(miPaste);

mEdit.add(miDelete);

//添加格式菜單項(xiàng)

mFormat.add(miFont);

mFormat.add(miLowtoCapital);

mFormat.add(miCapitaltoLow);

mFormat.add(miEncrypt);

mFormat.add(miDisencrypt);

//添加幫助菜單項(xiàng)

mHelp.add(miAboutNotepad);

//菜單條添加菜單

mb.add(mFile);

mb.add(mEdit);

mb.add(mFormat);

mb.add(mHelp);

//框架添加菜單條

mainFrame.setMenuBar( mb );

//初始字符串賦為空

tempString = "";

//添加文本區(qū)

mainFrame.add(ta, BorderLayout.CENTER);

mainFrame.setSize(800 , 500);

mainFrame.setLocation( 100 ,100);// 起始位置

mainFrame.setResizable(true);//不可更改大小

mainFrame.setVisible(true);

//mainFrame.pack();

//////////////////////////////////////////////////////////////////////////////////

////////////////////////////////增加監(jiān)視器////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////

//主框架

mainFrame.addWindowListener(new WindowAdapter (){ //關(guān)閉窗口

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

//文本區(qū)

ta.addKeyListener( new KeyAdapter(){

public void KeyTyped(KeyEvent e){

textValueChanged = true ; //鍵盤按鍵按下即導(dǎo)致文本修改

}

});

////////////////"文件"菜單://////////////////////

//新建

miNew.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

ta.replaceRange("", 0 , ta.getText().length()) ;//清空文本區(qū)的內(nèi)容

fileName = "";//文件名清空

}

});

//打開

miOpen.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e) {

FileDialog d=new FileDialog(mainFrame , "open file" , FileDialog.LOAD );//打開文件對(duì)話框

d.addWindowListener( new WindowAdapter(){ //關(guān)閉文件對(duì)話框窗口

public void windowClosing(WindowEvent ee){

System.exit(0);

}

});

d.setVisible(true);

File f = new File( d.getDirectory()+d.getFile() ); //建立新文件

fileName = d.getDirectory()+d.getFile();//得到文件名

char ch[] = new char [(int)f.length()];///用此文件的長度建立一個(gè)字符數(shù)組

try//異常處理

{

//讀出數(shù)據(jù),并存入字符數(shù)組ch中

BufferedReader bw = new BufferedReader( new FileReader(f) );

bw.read(ch);

bw.close();

}

catch( FileNotFoundException fe ){

System.out.println("file not found");

System.exit(0);

}

catch( IOException ie){

System.out.println("IO error");

System.exit(0);

}

String s =new String (ch);

ta.setText(s);//設(shè)置文本區(qū)為所打開文件的內(nèi)容

}

});

//保存

miSave.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e) {

if( fileName.equals("") ){ //如果文件沒有被保存過,即文件名為空

FileDialog d=new FileDialog(mainFrame , "save file" , FileDialog.SAVE );//保存文件對(duì)話框

d.addWindowListener( new WindowAdapter(){ //關(guān)閉文件對(duì)話框窗口

public void windowClosing(WindowEvent ee){

System.exit(0);

}

});

d.setVisible(true);

String s = ta.getText();//得到所輸入的文本內(nèi)容

try//異常處理

{

File f = new File( d.getDirectory()+d.getFile());//新建文件

fileName = d.getDirectory()+d.getFile();//得到文件名

BufferedWriter bw = new BufferedWriter( new FileWriter (f));//輸入到文件中

bw.write(s , 0 , s.length());

bw.close();

}

catch(FileNotFoundException fe_){

System.out.println("file not found");

System.exit(0);

}

catch( IOException ie_)

{

System.out.println(" IO error");

System.exit(0);

}

}

else //如果文件已經(jīng)保存過

{

String s = ta.getText();//得到所輸入的文本內(nèi)容

try//異常處理

{

File f = new File( fileName );//新建文件

BufferedWriter bw = new BufferedWriter( new FileWriter (f));//輸入到文件中

bw.write(s , 0 , s.length());

bw.close();

}

catch(FileNotFoundException fe_){

System.out.println("file not found");

System.exit(0);

}

catch( IOException ie_)

{

System.out.println(" IO error");

System.exit(0);

}

}

}

});

//另存為

miSaveAs.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e) {

FileDialog d=new FileDialog(mainFrame , "save file" , FileDialog.SAVE );//保存文件對(duì)話框

d.addWindowListener( new WindowAdapter(){ //關(guān)閉文件對(duì)話框窗口

public void windowClosing(WindowEvent ee){

System.exit(0);

}

});

d.setVisible(true);

String s = ta.getText();//得到所輸入的文本內(nèi)容

try//異常處理

{

File f = new File( d.getDirectory()+d.getFile());//新建文件

BufferedWriter bw = new BufferedWriter( new FileWriter (f));//輸入到文件中

bw.write(s , 0 , s.length());

bw.close();

}

catch(FileNotFoundException fe_){

System.out.println("file not found");

System.exit(0);

}

catch( IOException ie_)

{

System.out.println(" IO error");

System.exit(0);

}

}

});

//退出

miExit.addActionListener( new ActionListener(){ ///退出程序

public void actionPerformed(ActionEvent e){

System.exit(0);

}

});

////////////////"編輯"菜單:////////////////////

//剪切

miCut.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

tempString = ta.getSelectedText(); ///得到要復(fù)制的內(nèi)容,暫存在tempString中

StringBuffer tmp = new StringBuffer ( ta.getText());//臨時(shí)存儲(chǔ)文本

int start = ta.getSelectionStart(); //得到要?jiǎng)h除的字符串的起始位置

int len = ta.getSelectedText().length(); //得到要?jiǎng)h除的字符串的長度

tmp.delete( start , start+len); ///刪除所選中的字符串

ta.setText(tmp.toString());//用新文本設(shè)置原文本

}

});

//復(fù)制

miCopy.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

tempString = ta.getSelectedText(); ///得到要復(fù)制的內(nèi)容,暫存在tempString中

}

});

//粘貼

miPaste.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

StringBuffer tmp = new StringBuffer ( ta.getText());//臨時(shí)存儲(chǔ)文本

int start = ta.getSelectionStart(); //得到要粘貼的位置

tmp.insert(start , tempString);//查入要粘貼的內(nèi)容

ta.setText(tmp.toString());//用新文本設(shè)置原文本

}

});

//刪除

miDelete.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

StringBuffer tmp = new StringBuffer ( ta.getText());//臨時(shí)存儲(chǔ)文本

int start = ta.getSelectionStart(); //得到要?jiǎng)h除的字符串的起始位置

int len = ta.getSelectedText().length(); //得到要?jiǎng)h除的字符串的長度

tmp.delete( start , start+len); ///刪除所選中的字符串

ta.setText(tmp.toString());//用新文本設(shè)置原文本

}

});

////////////////"格式"菜單:////////////////////

//字體

miFont.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

final Dialog d = new Dialog ( mainFrame , "Font");//新建對(duì)話框

d.setLocation( 250 ,250);// 起始位置

d.setLayout( new BorderLayout());//表格布局

//////////////////////////上部分面板

Label l_font = new Label ("font");//font標(biāo)簽

Panel p_1 = new Panel();

p_1.add(l_font);

p_1.setVisible(true);

//////////////////////////中部分面板

List font_list = new List (6 , false);//字體列表

//添加字體項(xiàng)目

font_list.add("Plain");///普通字體

font_list.add("Bold"); ///粗體

font_list.add("Italic");//斜體

font_list.addItemListener( new MyItemListener_font() ); //字體增加監(jiān)視器

Panel p_2 = new Panel();

p_2.add(font_list);

p_2.setVisible(true);

//////////////////////////下部分面板

Button ok = new Button ("OK");

ok.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

d.dispose();

}

});

ok.setSize( new Dimension (20 , 5) );

Panel p_3 = new Panel();//下部分面板

p_3.add(ok);

p_3.setVisible(true);

//添加三個(gè)面板

d.add(p_1 , BorderLayout.NORTH);

d.add(p_2 , BorderLayout.CENTER);

d.add(p_3 , BorderLayout.SOUTH);

d.pack();

d.addWindowListener( new WindowAdapter(){ //關(guān)閉對(duì)話框窗口

public void windowClosing(WindowEvent ee){

d.dispose();

}

});

d.setVisible(true);

}

});

//小寫字母轉(zhuǎn)大寫

miLowtoCapital.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

String s = ta.getText();//得到所輸入的文本內(nèi)容

StringBuffer temp = new StringBuffer("");

for(int i = 0 ; is.length() ; i++){

if((int)s.charAt(i)=97 (int)s.charAt(i)=122 ){

temp.append((char)((int)s.charAt(i)-32));

}

else

temp.append(s.charAt(i));

}

s = new String(temp);

ta.setText(s);

}

});

//大寫字母轉(zhuǎn)小寫

miCapitaltoLow.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

String s = ta.getText();//得到所輸入的文本內(nèi)容

StringBuffer temp = new StringBuffer("");

for(int i = 0 ; is.length() ; i++){

if((int)s.charAt(i)=65 (int)s.charAt(i)=90 ){

temp.append((char)((int)s.charAt(i)+32));

}

else

temp.append(s.charAt(i));

}

s = new String(temp);

ta.setText(s);

}

});

//加密

miEncrypt.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

String s = ta.getText();//得到所輸入的文本內(nèi)容

StringBuffer temp = new StringBuffer("");

for(int i = 0 ; is.length() ; i++){

if(s.charAt(i)=40 s.charAt(i)=125){

if(i%2==0){

temp.append((char)(s.charAt(i) + 1 ));

}

else

temp.append((char)(s.charAt(i) - 1 ));

}

else

temp.append(s.charAt(i));

}

s = new String(temp);

ta.setText(s);

}

});

//解密

miDisencrypt.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

String s = ta.getText();//得到所輸入的文本內(nèi)容

StringBuffer temp = new StringBuffer("");

for(int i = 0 ; is.length() ; i++){

if(s.charAt(i)=40 s.charAt(i)=125){

if(i%2==0){

temp.append((char)(s.charAt(i) - 1 ));

}

else

temp.append((char)(s.charAt(i) + 1 ));

}

else

temp.append(s.charAt(i));

}

s = new String(temp);

ta.setText(s);

}

});

////////////////"幫助"菜單:////////////////////

//關(guān)于記事本

miAboutNotepad.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent e){

final Dialog d = new Dialog ( mainFrame , "AboutNotepad");//新建對(duì)話框

TextArea t = new TextArea("\nwelcome to use Notepad " + "\n\n" + "Copyright@Launching " + "\n\n" + "free software" + "\n\n" + "v0.99");//添加標(biāo)簽

t.setSize( new Dimension ( 5 , 5));

t.setEditable(false);

d.setResizable(false);//不可調(diào)整大小

d.add(t);

d.pack();

d.addWindowListener( new WindowAdapter(){ //關(guān)閉對(duì)話框窗口

public void windowClosing(WindowEvent ee){

d.dispose();

}

});

d.setLocation( 100 ,250);// 起始位置

d.setVisible(true);

}

});

}

class MyItemListener_font implements ItemListener { //字體監(jiān)聽器

public void itemStateChanged(ItemEvent e) {

id_font = ((java.awt.List)e.getSource()).getSelectedIndex();

switch( id_font){

case 0:{

ta.setFont(new Font("Times New Roman", Font.PLAIN ,ta.getFont().getSize()) );//普通文字

break;

}

case 1:{

ta.setFont(new Font("Times New Roman" , Font.BOLD ,ta.getFont().getSize()) );//粗體文字

break;

}

case 2:{

ta.setFont(new Font("Times New Roman" , Font.ITALIC ,ta.getFont().getSize()) );//斜體文字

break;

}

}

}

}

/////////////////////////////////////////主函數(shù)///////////////////////////////////////////////////

public static void main(String arg[]){

Notepad test = new Notepad(); ///創(chuàng)建記事本

}

//////////////////////////////////////////////////////////////////////////////////////////////////

}

java語言寫一個(gè)文本編輯器的源代碼 要能測(cè)試通過的!用Eclipse能運(yùn)行通過的!

一. 高亮的內(nèi)容:

需要高亮的內(nèi)容有:

1. 關(guān)鍵字, 如 public, int, true 等.

2. 運(yùn)算符, 如 +, -, *, /等

3. 數(shù)字

4. 高亮字符串, 如 "example of string"

5. 高亮單行注釋

6. 高亮多行注釋

二. 實(shí)現(xiàn)高亮的核心方法:

StyledDocument.setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace)

三. 文本編輯器選擇.

Java中提供的多行文本編輯器有: JTextComponent, JTextArea, JTextPane, JEditorPane等, 都可以使用. 但是因?yàn)檎Z法著色中文本要使用多種風(fēng)格的樣式, 所以這些文本編輯器的document要使用StyledDocument.

JTextArea使用的是PlainDocument, 此document不能進(jìn)行多種格式的著色.

JTextPane, JEditorPane使用的是StyledDocument, 默認(rèn)就可以使用.

為了實(shí)現(xiàn)語法著色, 可以繼承自DefaultStyledDocument, 設(shè)置其為這些文本編輯器的documet, 或者也可以直接使用JTextPane, JEditorPane來做. 為了方便, 這里就直接使用JTextPane了.

四. 何時(shí)進(jìn)行著色.

當(dāng)文本編輯器中有字符被插入或者刪除時(shí), 文本的內(nèi)容就發(fā)生了變化, 這時(shí)檢查, 進(jìn)行著色.

為了監(jiān)視到文本的內(nèi)容發(fā)生了變化, 要給document添加一個(gè)DocumentListener監(jiān)聽器, 在他的removeUpdate和insertUpdate中進(jìn)行著色處理.

而changedUpdate方法在文本的屬性例如前景色, 背景色, 字體等風(fēng)格改變時(shí)才會(huì)被調(diào)用.

@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 {

// 因?yàn)閯h除后光標(biāo)緊接著影響的單詞兩邊, 所以長度就不需要了

colouring((StyledDocument) e.getDocument(), e.getOffset(), 0);

} catch (BadLocationException e1) {

e1.printStackTrace();

}

}

五. 著色范圍:

pos: 指變化前光標(biāo)的位置.

len: 指變化的字符數(shù).

例如有關(guān)鍵字public, int

單詞"publicint", 在"public"和"int"中插入一個(gè)空格后變成"public int", 一個(gè)單詞變成了兩個(gè), 這時(shí)對(duì)"public" 和 "int"進(jìn)行著色.

著色范圍是public中p的位置和int中t的位置加1, 即是pos前面單詞開始的下標(biāo)和pos+len開始單詞結(jié)束的下標(biāo). 所以上例中要著色的范圍是"public int".

提供了方法indexOfWordStart來取得pos前單詞開始的下標(biāo), 方法indexOfWordEnd來取得pos后單詞結(jié)束的下標(biāo).

public int indexOfWordStart(Document doc, int pos) throws BadLocationException {

// 從pos開始向前找到第一個(gè)非單詞字符.

for (; pos 0 isWordCharacter(doc, pos - 1); --pos);

return pos;

}

public int indexOfWordEnd(Document doc, int pos) throws BadLocationException {

// 從pos開始向前找到第一個(gè)非單詞字符.

for (; isWordCharacter(doc, pos); ++pos);

return pos;

}

一個(gè)字符是單詞的有效字符: 是字母, 數(shù)字, 下劃線.

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);

六. 關(guān)鍵字著色.

從著色范圍的開始下標(biāo)起進(jìn)行判斷, 如果是以字母開或者下劃線開頭, 則說明是單詞, 那么先取得這個(gè)單詞, 如果這個(gè)單詞是關(guān)鍵字, 就進(jìn)行關(guān)鍵字著色, 如果不是, 就進(jìn)行普通的著色. 著色完這個(gè)單詞后, 繼續(xù)后面的著色處理. 已經(jīng)著色過的字符, 就不再進(jìn)行著色了.

public void colouring(StyledDocument doc, int pos, int len) throws BadLocationException {

// 取得插入或者刪除后影響到的單詞.

// 例如"public"在b后插入一個(gè)空格, 就變成了:"pub lic", 這時(shí)就有兩個(gè)單詞要處理:"pub"和"lic"

// 這時(shí)要取得的范圍是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為處理后的最后一個(gè)下標(biāo)

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); // 要進(jìn)行著色的單詞

if (keywords.contains(word)) {

// 如果是關(guān)鍵字, 就進(jìn)行關(guān)鍵字的著色, 否則使用普通的著色.

// 這里有一點(diǎn)要注意, 在insertUpdate和removeUpdate的方法調(diào)用的過程中, 不能修改doc的屬性.

// 但我們又要達(dá)到能夠修改doc的屬性, 所以把此任務(wù)放到這個(gè)方法的外面去執(zhí)行.

// 實(shí)現(xiàn)這一目的, 可以使用新線程, 但放到swing的事件隊(duì)列里去處理更輕便一點(diǎn).

SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, keywordStyle));

} else {

SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, normalStyle));

}

return wordEnd;

}

因?yàn)樵趇nsertUpdate和removeUpdate方法中不能修改document的屬性, 所以著色的任務(wù)放到這兩個(gè)方法外面, 所以使用了SwingUtilities.invokeLater來實(shí)現(xiàn).

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 {

// 這里就是對(duì)字符進(jìn)行著色

doc.setCharacterAttributes(pos, len, style, true);

} catch (Exception e) {}

}

}

七: 源碼

關(guān)鍵字著色的完成代碼如下, 可以直接編譯運(yùn)行. 對(duì)于數(shù)字, 運(yùn)算符, 字符串等的著色處理在以后的教程中會(huì)繼續(xù)進(jìn)行詳解.

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);

}

}

/**

* 當(dāng)文本輸入?yún)^(qū)的有字符插入或者刪除時(shí), 進(jìn)行高亮.

*

* 要進(jìn)行語法高亮, 文本輸入組件的document要是styled document才行. 所以不要用JTextArea. 可以使用JTextPane.

*

* @author Biao

*

*/

class SyntaxHighlighter implements DocumentListener {

private SetString keywords;

private Style keywordStyle;

private Style normalStyle;

public SyntaxHighlighter(JTextPane editor) {

// 準(zhǔn)備著色使用的樣式

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);

// 準(zhǔn)備關(guān)鍵字

keywords = new HashSetString();

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后插入一個(gè)空格, 就變成了:"pub lic", 這時(shí)就有兩個(gè)單詞要處理:"pub"和"lic"

// 這時(shí)要取得的范圍是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為處理后的最后一個(gè)下標(biāo)

start = colouringWord(doc, start);

} else {

SwingUtilities.invokeLater(new ColouringTask(doc, start, 1, normalStyle));

++start;

}

}

}

/**

* 對(duì)單詞進(jìn)行著色, 并返回單詞結(jié)束的下標(biāo).

*

* @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)) {

// 如果是關(guān)鍵字, 就進(jìn)行關(guān)鍵字的著色, 否則使用普通的著色.

// 這里有一點(diǎn)要注意, 在insertUpdate和removeUpdate的方法調(diào)用的過程中, 不能修改doc的屬性.

// 但我們又要達(dá)到能夠修改doc的屬性, 所以把此任務(wù)放到這個(gè)方法的外面去執(zhí)行.

// 實(shí)現(xiàn)這一目的, 可以使用新線程, 但放到swing的事件隊(duì)列里去處理更輕便一點(diǎn).

SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, keywordStyle));

} else {

SwingUtilities.invokeLater(new ColouringTask(doc, pos, wordEnd - pos, normalStyle));

}

return wordEnd;

}

/**

* 取得在文檔中下標(biāo)在pos處的字符.

*

* 如果pos為doc.getLength(), 返回的是一個(gè)文檔的結(jié)束符, 不會(huì)拋出異常. 如果pos0, 則會(huì)拋出異常.

* 所以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);

}

/**

* 取得下標(biāo)為pos時(shí), 它所在的單詞開始的下標(biāo). ?±wor^d?± (^表示pos, ?±表示開始或結(jié)束的下標(biāo))

*

* @param doc

* @param pos

* @return

* @throws BadLocationException

*/

public int indexOfWordStart(Document doc, int pos) throws BadLocationException {

// 從pos開始向前找到第一個(gè)非單詞字符.

for (; pos 0 isWordCharacter(doc, pos - 1); --pos);

return pos;

}

/**

* 取得下標(biāo)為pos時(shí), 它所在的單詞結(jié)束的下標(biāo). ?±wor^d?± (^表示pos, ?±表示開始或結(jié)束的下標(biāo))

*

* @param doc

* @param pos

* @return

* @throws BadLocationException

*/

public int indexOfWordEnd(Document doc, int pos) throws BadLocationException {

// 從pos開始向前找到第一個(gè)非單詞字符.

for (; isWordCharacter(doc, pos); ++pos);

return pos;

}

/**

* 如果一個(gè)字符是字母, 數(shù)字, 下劃線, 則返回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 {

// 因?yàn)閯h除后光標(biāo)緊接著影響的單詞兩邊, 所以長度就不需要了

colouring((StyledDocument) e.getDocument(), e.getOffset(), 0);

} catch (BadLocationException e1) {

e1.printStackTrace();

}

}

/**

* 完成著色任務(wù)

*

* @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 {

// 這里就是對(duì)字符進(jìn)行著色

doc.setCharacterAttributes(pos, len, style, true);

} catch (Exception e) {}

}

}

}

用JAVA編寫一個(gè)圖形應(yīng)用程序,可以是一個(gè)簡(jiǎn)單的文本編輯器、計(jì)算器等等。 求完整代碼

//百度文庫找的,可費(fèi)了我的財(cái)富值了,你可要把分給我呀。

package lee;

/*文件名:Calculator.java

*說明:簡(jiǎn)易科學(xué)計(jì)算器

*/

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Calculator extends Frame implements ActionListener, WindowListener

{

private Container container;

private GridBagLayout layout;

private GridBagConstraints constraints;

private JTextField displayField; //計(jì)算結(jié)果顯示區(qū)

private String lastCommand; //保存+,-,*,/,=命令0

private double result; //保存計(jì)算結(jié)果

private boolean start; //判斷是否為數(shù)字的開始

private JMenuBar menubar;

private JMenuItem m_exit,m2_ejz,m2_bjz;

private Dialog dialog;

private Label label_dialog;

private JButton button_sqrt,button_plusminus,button_CE,button_cancel,button_1,button_2,

button_3,button_4,button_5,button_6,button_7,button_8,button_9,button_0,

button_plus,button_minus,button_multiply,button_divide,button_point,

button_equal,button_log,button_tan,button_cos,button_sin,button_exp;

public Calculator() //構(gòu)造方法設(shè)置布局、為按鈕注冊(cè)事件監(jiān)聽器

{

super("Calculator");

this.setLocation(240,200);

this.setSize(350,300);

this.setResizable(true);

this.setLayout(new GridLayout(7,1));

this.addmyMenu(); //調(diào)用成員方法添加菜單

displayField=new JTextField(30);

this.add(displayField);

displayField.setEditable(true);

start=true;

result=0;

lastCommand = "=";

JPanel panel0=new JPanel();

panel0.setLayout(new GridLayout(1,4,4,4));

JPanel panel1=new JPanel();

panel1.setLayout(new GridLayout(1,5,4,4));

this.add(panel1);

button_sqrt=new JButton("sqrt");

button_plusminus=new JButton("+/-");

button_exp=new JButton("exp");

button_CE=new JButton("退格");

button_cancel=new JButton("C");

JPanel panel2=new JPanel();

panel2.setLayout(new GridLayout(1,5,4,4));

this.add(panel2);

button_7=new JButton("7");

button_8=new JButton("8");

button_9=new JButton("9");

button_log=new JButton("log");

button_divide=new JButton("/");

JPanel panel3=new JPanel();

panel3.setLayout(new GridLayout(1,5,4,4));

this.add(panel3);

button_4=new JButton("4");

button_5=new JButton("5");

button_6=new JButton("6");

button_tan=new JButton("tan");

button_multiply=new JButton("*");

JPanel panel4=new JPanel();

panel4.setLayout(new GridLayout(1,5,4,4));

this.add(panel4);

button_1=new JButton("1");

button_2=new JButton("2");

button_3=new JButton("3");

button_cos=new JButton("cos");

button_minus=new JButton("-");

JPanel panel5=new JPanel();

panel5.setLayout(new GridLayout(1,5,4,4));

this.add(panel5);

button_0=new JButton("0");

button_point=new JButton(".");

button_equal=new JButton("=");

button_sin=new JButton("sin");

button_plus=new JButton("+");

panel1.add(button_sqrt);

panel1.add(button_plusminus);

panel1.add(button_exp);

panel1.add(button_CE);

panel1.add(button_cancel);

panel2.add(button_7);

panel2.add(button_8);

panel2.add(button_9);

panel2.add(button_log);

panel2.add(button_divide);

panel3.add(button_4);

panel3.add(button_5);

panel3.add(button_6);

panel3.add(button_tan);

panel3.add(button_multiply);

panel4.add(button_1);

panel4.add(button_2);

panel4.add(button_3);

panel4.add(button_cos);

panel4.add(button_minus);

panel5.add(button_0);

panel5.add(button_point);

panel5.add(button_equal);

panel5.add(button_sin);

panel5.add(button_plus);

button_sqrt.addActionListener(this);

button_plusminus.addActionListener(this);

button_exp.addActionListener(this);

button_CE.addActionListener(this);

button_cancel.addActionListener(this);

button_7.addActionListener(this);

button_8.addActionListener(this);

button_9.addActionListener(this);

button_log.addActionListener(this);

button_divide.addActionListener(this);

button_4.addActionListener(this);

button_5.addActionListener(this);

button_6.addActionListener(this);

button_tan.addActionListener(this);

button_multiply.addActionListener(this);

button_1.addActionListener(this);

button_2.addActionListener(this);

button_3.addActionListener(this);

button_cos.addActionListener(this);

button_minus.addActionListener(this);

button_0.addActionListener(this);

button_point.addActionListener(this);

button_equal.addActionListener(this);

button_sin.addActionListener(this);

button_plus.addActionListener(this);

this.addWindowListener(new WinClose()); //注冊(cè)窗口監(jiān)聽器

this.setVisible(true);

}

private void addmyMenu() //菜單的添加

{

JMenuBar menubar=new JMenuBar();

this.add(menubar);

JMenu m1=new JMenu("選項(xiàng)");

JMenu m2=new JMenu("進(jìn)制轉(zhuǎn)換");

JMenuItem m1_exit=new JMenuItem("退出");

m1_exit.addActionListener(this);

JMenuItem m2_ejz=new JMenuItem("二進(jìn)制");

m2_ejz.addActionListener(this);

JMenuItem m2_bjz=new JMenuItem("八進(jìn)制");

m2_bjz.addActionListener(this);

JMenu m3 = new JMenu(" 幫助");

JMenuItem m3_Help = new JMenuItem("用法");

m3_Help.addActionListener(this);

dialog = new Dialog(this,"提示",true); //模式窗口

dialog.setSize(240,80);

label_dialog = new Label("",Label.CENTER); //標(biāo)簽的字符串為空,居中對(duì)齊

dialog.add(label_dialog);

dialog.addWindowListener(this); //為對(duì)話框注冊(cè)窗口事件監(jiān)聽器

m1.add(m1_exit);

menubar.add(m1);

m2.add(m2_ejz);

m2.add(m2_bjz);

menubar.add(m2);

m3.add(m3_Help);

menubar.add(m3); }

public void actionPerformed(ActionEvent e) //按鈕的單擊事件處理方法

{

if(e.getSource().equals(button_1)||e.getSource().equals(button_2)||

e.getSource().equals(button_3)||e.getSource().equals(button_4)||

e.getSource().equals(button_5)|| e.getSource().equals(button_6)||

e.getSource().equals(button_7)|| e.getSource().equals(button_8)||

e.getSource().equals(button_9) ||e.getSource().equals(button_0)||

e.getSource().equals(button_point)||e.getSource().equals(button_plusminus)||

e.getSource().equals(button_cancel)||e.getSource().equals(button_CE))

{ //非運(yùn)算符的處理方法

String input=e.getActionCommand();

if (start)

{

displayField.setText("");

start=false;

if(input.equals("+/-"))

displayField.setText(displayField.getText()+"-");

}

if(!input.equals("+/-"))

{

String str=displayField.getText();

if(input.equals("退格")) //退格鍵的實(shí)現(xiàn)方法

{

if(str.length()0)

displayField.setText(str.substring(0,str.length()-1));

}

else if(input.equals("C")) //清零鍵的實(shí)現(xiàn)方法

{

displayField.setText("0");

start=true;

}

else

displayField.setText(displayField.getText()+input);

}

}

else if (e.getActionCommand()=="二進(jìn)制") //二進(jìn)制的轉(zhuǎn)換

{

int n=Integer.parseInt(displayField.getText());

displayField.setText(Integer.toBinaryString(n));

}

else if (e.getActionCommand()=="八進(jìn)制") //八進(jìn)制的轉(zhuǎn)換

{

int n=Integer.parseInt(displayField.getText());

displayField.setText(Integer.toOctalString(n));

}

else if (e.getActionCommand()=="退出") //選項(xiàng)中退出的處理方法

{

System.exit(0);

}

else if (e.getActionCommand()=="用法") //按下'幫助'菜單欄中用法的處理方法

{

label_dialog.setText("sqrt,exp等鍵是先輸運(yùn)算符再輸數(shù)字\n");

dialog.setLocation(400,250);

dialog.setVisible(true);

}

else //各運(yùn)算符的識(shí)別

{

String command=e.getActionCommand();

if(start)

{

lastCommand=command;

}

else

{

calculate(Double.parseDouble(displayField.getText()));

lastCommand=command;

start=true;

}

}

}

public void calculate(double x) //各運(yùn)算符的具體運(yùn)算方法

{

double d=0;

if (lastCommand.equals("+"))

result+= x;

else if (lastCommand.equals("-"))

result-=x;

else if (lastCommand.equals("*"))

result*=x;

else if (lastCommand.equals("/"))

result/=x;

else if (lastCommand.equals("="))

result=x;

else if (lastCommand.equals("sqrt"))

{

d=Math.sqrt(x);

result=d;

}

else if (lastCommand.equals("exp"))

{

d=Math.exp(x);

result=d;

}

else if (lastCommand.equals("log"))

{

d=Math.log(x);

result=d;

}

else if (lastCommand.equals("tan"))

{

d=Math.tan(x);

result=d;

}

else if (lastCommand.equals("cos"))

{

d=Math.cos(x);

result=d;

}

else if (lastCommand.equals("sin"))

{

d=Math.sin(x);

result=d;

}

displayField.setText(""+ result);

}

public void windowClosing(WindowEvent e)

{

if(e.getSource()==dialog)

dialog.setVisible(false); //隱藏對(duì)話框

else

System.exit(0);

}

public void windowOpened(WindowEvent e) { }

public void windowActivated(WindowEvent e) { }

public void windowDeactivated(WindowEvent e) { }

public void windowClosed(WindowEvent e) { }

public void windowIconified(WindowEvent e) { }

public void windowDeiconified(WindowEvent e) { }

public static void main(String args[])

{

Calculator calculator=new Calculator();

}

}

class WinClose implements WindowListener

{

public void windowClosing(WindowEvent e) //單擊窗口關(guān)閉按鈕時(shí)觸發(fā)并執(zhí)行實(shí)現(xiàn)窗口監(jiān)聽器接口中的方法

{

System.exit(0); //結(jié)束程序運(yùn)行

}

public void windowOpened(WindowEvent e){}

public void windowActivated(WindowEvent e){}

public void windowDeactivated(WindowEvent e){}

public void windowClosed(WindowEvent e){}

public void windowIconified(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

}

如何用java編寫一個(gè)簡(jiǎn)單的文本編輯器?

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={"粗體","傾斜","常規(guī)","粗斜"};

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);

求一個(gè)用Java編寫的文本編輯器代碼

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.io.*;

public class MyTextEditor extends JFrame implements ActionListener,ItemListener,MouseListener

{

private File file;

private JTextArea textarea;

private JRadioButtonMenuItem rbmi_red,rbmi_blue,rbmi_green;

private JMenuItem menuitem_copy,menuitem_cut,menuitem_paste,menuitem_seek;

private JMenuItem menuitem_song,menuitem_fang,menuitem_kai;//字體變量

private JMenuItem menuitem_normal,menuitem_bold,menuitem_italic;//字形變量

private JMenuItem menuitem_20,menuitem_30,menuitem_40;//字號(hào)變量

private JMenuItem menuitem_exit,menuitem_infor;

private JPopupMenu popupmenu;

private JMenuItem menuitem_red,menuitem_green,menuitem_blue;

private JDialog dialog,dialog1;

private JButton button_seek;

private JTextField textfield_seek;

private JLabel label_seek,label_infor;

String seek;

public MyTextEditor()

{

super("文本編輯器");

this.setSize(400,300);

this.setLocation(360,300);

this.setDefaultCloseOperation(HIDE_ON_CLOSE);

Container ss=this.getContentPane();

this.textarea = new JTextArea();

JScrollPane dd=new JScrollPane(textarea);

ss.add(dd);

textarea.addMouseListener(this);

this.addMenu();

this.setVisible(true);

this.Dialog();

this.Dialog1();

this.file = null;

}

public MyTextEditor(String filename)

{

this();

if (filename!=null)

{

this.file = new File(filename);

this.setTitle(filename);

this.textarea.setText(this.readFromFile());

}

}

public MyTextEditor(File file)

{

this();

if (file!=null)

{

this.file = file;

this.setTitle(this.file.getName());

this.textarea.setText(this.readFromFile());

}

}

public void Dialog() //建立對(duì)話框的方法

{

dialog=new JDialog(this,"查找",true);

dialog.setLayout(new FlowLayout());

dialog.setSize(200,90);

label_seek=new JLabel("查找內(nèi)容");

dialog.add(label_seek);

textfield_seek=new JTextField(10);

dialog.add(textfield_seek);

button_seek=new JButton("查找");

dialog.add(button_seek);

button_seek.addActionListener(this);

}

public void Dialog1()

{

dialog1=new JDialog(this,"專利",true);

dialog1.setLayout(new FlowLayout());

dialog1.setSize(200,100);

label_infor=new JLabel("劉同虎制作");

dialog1.add(label_infor);

}

public void addMenu()

{

JMenuBar menubar = new JMenuBar();

this.setJMenuBar(menubar);

JMenu menu_file = new JMenu("文件"); //文件菜單

menubar.add(menu_file);

JMenuItem menuitem_open = new JMenuItem("打開");

menu_file.add(menuitem_open);

menuitem_open.addActionListener(this);

JMenuItem menuitem_save = new JMenuItem("保存");

menu_file.add(menuitem_save);

menuitem_save.addActionListener(this);

JMenuItem menuitem_saveas = new JMenuItem("另存為");

menu_file.add(menuitem_saveas);

menuitem_saveas.addActionListener(this);

menuitem_exit=new JMenuItem("退出" );

menu_file.add(menuitem_exit);

menuitem_exit.addActionListener(this);

menuitem_infor=new JMenuItem("信息");

menu_file.add(menuitem_infor);

menuitem_infor.addActionListener(this);

JMenu menu_editor=new JMenu("編輯");//編輯菜單

menubar.add(menu_editor);

menuitem_seek=new JMenuItem("查找");

menu_editor.add(menuitem_seek);

menuitem_seek.addActionListener(this);

menuitem_copy=new JMenuItem("復(fù)制");

menuitem_copy.addActionListener(this);

menu_editor.add(menuitem_copy);

menuitem_cut=new JMenuItem("剪切");

menu_editor.add(menuitem_cut);

menuitem_cut.addActionListener(this);

menuitem_paste=new JMenuItem("粘貼");

menu_editor.add(menuitem_paste);

menuitem_paste.addActionListener(this);

JMenuItem menu_color=new JMenu("顏色");//顏色菜單

menu_editor.add(menu_color);

ButtonGroup buttongroup=new ButtonGroup();

rbmi_red=new JRadioButtonMenuItem("紅",true);

buttongroup.add(rbmi_red);

menu_color.add(rbmi_red);

rbmi_red.addItemListener(this);

rbmi_blue=new JRadioButtonMenuItem("藍(lán)",true);

buttongroup.add(rbmi_blue);

menu_color.add(rbmi_blue);

rbmi_blue.addItemListener(this);

rbmi_green=new JRadioButtonMenuItem("綠",true);

buttongroup.add(rbmi_green);

menu_color.add(rbmi_green);

rbmi_green.addItemListener(this);

JMenu menu_font=new JMenu("設(shè)置字體");//設(shè)置字體菜單

menubar.add(menu_font);

menuitem_song=new JMenuItem("宋體");

menu_font.add(menuitem_song);

menuitem_song.addActionListener(this);

menuitem_fang=new JMenuItem("仿宋");

menu_font.add(menuitem_fang);

menuitem_fang.addActionListener(this);

menuitem_kai=new JMenuItem("楷體");

menu_font.add(menuitem_kai);

menuitem_kai.addActionListener(this);

JMenu menu_style=new JMenu("設(shè)置字形");//設(shè)置字形菜單

menubar.add(menu_style);

menuitem_bold=new JMenuItem("粗體");

menu_style.add(menuitem_bold);

menuitem_bold.addActionListener(this);

menuitem_italic=new JMenuItem("斜體");

menu_style.add(menuitem_italic);

menuitem_italic.addActionListener(this);

JMenu menu_size=new JMenu("設(shè)置字號(hào)"); //設(shè)置字號(hào)菜單

menubar.add(menu_size);

menuitem_20=new JMenuItem("20");

menu_size.add(menuitem_20);

menuitem_20.addActionListener(this);

menuitem_30=new JMenuItem("30");

menu_size.add(menuitem_30);

menuitem_30.addActionListener(this);

menuitem_40=new JMenuItem("40");

menu_size.add(menuitem_40);

menuitem_40.addActionListener(this);

popupmenu=new JPopupMenu(); //快捷菜單

JMenuItem menuitem_red=new JMenuItem("紅色");

popupmenu.add(menuitem_red);

menuitem_red.addActionListener(this);

JMenuItem menuitem_green=new JMenuItem("綠色");

popupmenu.add(menuitem_green);

menuitem_green.addActionListener(this);

menuitem_blue=new JMenuItem("藍(lán)色");

popupmenu.add(menuitem_blue);

menuitem_blue.addActionListener(this);

textarea.add(popupmenu); //向文本區(qū)內(nèi)添加快捷菜單

}

public void writeToFile(String lines) //寫文件

{

try

{

FileWriter fout = new FileWriter(this.file);

fout.write(lines+"\r\n");

fout.close();

}

catch (IOException ioex)

{

return;

}

}

public String readFromFile() //讀文件

{

try

{

FileReader fin = new FileReader(this.file);

BufferedReader bin = new BufferedReader(fin);

String aline="", lines="";

do

{

aline = bin.readLine();

if (aline!=null)

lines += aline + "\r\n";

} while (aline!=null);

bin.close();

fin.close();

return lines;

}

catch (IOException ioex)

{

return null;

}

}

java語言寫一個(gè)文本編輯器的源代碼

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);

}

}

//保存文件的監(jiān)聽

class savel implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

JFileChooser jf = new JFileChooser();

jf.showSaveDialog(NotePad.this);

}

}

//打印的監(jiān)聽 ?

class printl implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

// PrintWriter p = new PrintWriter(NotePad.this);

}

}

//退出記事本的監(jiān)聽

class exitl implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

System.exit(0);//退出

}

}

//拷貝的監(jiān)聽

class copyl implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

jta.copy();

}

}

//粘貼的監(jiān)聽

class pastel implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

jta.paste();

}

}

//剪切的監(jiān)聽

class cutl implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

jta.cut();

}

}

//查找的監(jiān)聽

//添加日期的監(jiān)聽

class datel implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

Date d=new Date();

jta.append(d.toString());

}

}

//構(gòu)造函數(shù)

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 copyl());

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);

}

//主函數(shù),程序入口點(diǎn)

public static void main(String s[])

{

new NotePad();

}

}

當(dāng)前文章:java實(shí)現(xiàn)編輯器的代碼 java實(shí)現(xiàn)編輯器的代碼是什么
轉(zhuǎn)載源于:http://chinadenli.net/article26/hipscg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化建站公司網(wǎng)站排名網(wǎng)頁設(shè)計(jì)公司軟件開發(fā)手機(jī)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作