网站首页 > 文章中心 > 其它

java编辑器代码大全

作者:小编 更新时间:2023-10-06 13:57:47 浏览量:108人看过

一. 高亮的内容:

需要高亮的内容有:

java编辑器代码大全-图1

① 关键字, 如 public, int, true 等.

二. 实现高亮的核心方法:

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

JTextArea使用的是PlainDocument, 此document不能进行多种格式的着色.

JTextPane, JEditorPane使用的是StyledDocument, 默认就可以使用.

四. 何时进行着色.

为了监视到文本的内容发生了变化, 要给document添加一个DocumentListener监听器, 在他的removeUpdate和insertUpdate中进行着色处理.

而changedUpdate方法在文本的属性例如前景色, 背景色, 字体等风格改变时才会被调用.

@Override

public void changedUpdate(DocumentEvent e) {

}

public void insertUpdate(DocumentEvent e) {

java编辑器代码大全-图2

try {

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

} catch (BadLocationException e1) {

e1.printStackTrace();

public void removeUpdate(DocumentEvent e) {

// 因为删除后光标紧接着影响的单词两边, 所以长度就不需要了

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

五. 着色范围:

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 {

for (; isWordCharacter(doc, pos); ++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后面的位置

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

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() {

// 这里就是对字符进行着色

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.setVisible(true);

/**

* 当文本输入区的有字符插入或者删除时, 进行高亮.

*

* 要进行语法高亮, 文本输入组件的document要是styled document才行. 所以不要用JTextArea. 可以使用JTextPane.

* @author Biao

*/

class SyntaxHighlighter implements DocumentListener {

private SetString 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 HashSetString();

keywords.add("public");

keywords.add("protected");

keywords.add("private");

keywords.add("float");

keywords.add("double");

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

* 对单词进行着色, 并返回单词结束的下标.

* @param doc

* @param pos

* @return

* @throws BadLocationException

String word = doc.getText(pos, wordEnd - pos);

* 取得在文档中下标在pos处的字符.

* 如果pos为doc.getLength(), 返回的是一个文档的结束符, 不会抛出异常. 如果pos0, 则会抛出异常.

* 所以pos的有效值是[0, doc.getLength()]

public char getCharAt(Document doc, int pos) throws BadLocationException {

return doc.getText(pos, 1).charAt(0);

* 取得下标为pos时, 它所在的单词开始的下标. ?≡wor^d?≡ (^表示pos, ?≡表示开始或结束的下标)

* 取得下标为pos时, 它所在的单词结束的下标. ?≡wor^d?≡ (^表示pos, ?≡表示开始或结束的下标)

* 如果一个字符是字母, 数字, 下划线, 则返回true.

char ch = getCharAt(doc, pos);

* 完成着色任务

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

JFileChooser jf = new JFileChooser();

jf.showSaveDialog(NotePad.this);

//打印的监听 ?

class printl implements ActionListener

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

//退出记事本的监听

class exitl implements ActionListener

System.exit(0);//退出

//拷贝的监听

class copyl implements ActionListener

jta.copy();

//粘贴的监听

class pastel implements ActionListener

jta.paste();

//剪切的监听

class cutl implements ActionListener

jta.cut();

//查找的监听

//添加日期的监听

class datel implements ActionListener

Date d=new Date();

jta.append(d.toString());

//构造函数

public NotePad()

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

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

jmi=new JMenuItem("Paste");

jmi.addActionListener(new pastel());

mEdit.addSeparator(); //添加分割线

jmi=new JMenuItem("Find");

jmi=new JMenuItem("FindNext");

mEdit.addSeparator();

jmi=new JMenuItem("Select All");

jmi=new JMenuItem("Date/Time");

jmi.addActionListener(new datel());

jmb.add(mFile);

jmb.add(mEdit);

this.setJMenuBar(jmb);

this.getContentPane().add(jsp);

this.setVisible(true);

//主函数,程序入口点

public static void main(String s[])

new NotePad();

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_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()

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

java编辑器代码大全-图3

public MyTextEditor(File file)

if (file!=null)

this.file = file;

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

public void Dialog() //建立对话框的方法

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

dialog.setLayout(new FlowLayout());

label_seek=new JLabel("查找内容");

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

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

menubar.add(menu_editor);

menuitem_seek=new JMenuItem("查找");

menu_editor.add(menuitem_seek);

menuitem_seek.addActionListener(this);

menuitem_copy=new JMenuItem("复制");

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("蓝",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("设置字体");//设置字体菜单

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("设置字形");//设置字形菜单

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("设置字号"); //设置字号菜单

menubar.add(menu_size);

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("蓝色");

popupmenu.add(menuitem_blue);

menuitem_blue.addActionListener(this);

textarea.add(popupmenu); //向文本区内添加快捷菜单

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() //读文件

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;

return null;

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章