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

十多年的望城網(wǎng)站建設(shè)經(jīng)驗(yàn),針對設(shè)計(jì)、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。網(wǎng)絡(luò)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整望城建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。創(chuàng)新互聯(lián)從事“望城網(wǎng)站設(shè)計(jì)”,“望城網(wǎng)站推廣”以來,每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。
package lee;
/*文件名:Calculator.java
*說明:簡易科學(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è)置布局、為按鈕注冊事件監(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()); //注冊窗口監(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)簽的字符串為空,居中對齊
dialog.add(label_dialog);
dialog.addWindowListener(this); //為對話框注冊窗口事件監(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)算符的識別
{
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); //隱藏對話框
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){}
}
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);
1.確定數(shù)格式,編寫記錄類
Record{
//記錄編號
private int id;
//提醒時(shí)間
private Time t;
//提醒信息
private String info;
}
2.確定數(shù)據(jù)訪問方式,可以通過文件也可以通過數(shù)據(jù)庫。
寫一個(gè)數(shù)據(jù)訪問類,例如用文件的形式
DataAccesser{
private static syncronized File file;
//構(gòu)造函數(shù),進(jìn)行file初始化
public static DataAccesser(){
}
//寫入記錄
public static void write(Record){
}
//根據(jù)時(shí)間讀取記錄
public static Record read(int id){
}
//根據(jù)時(shí)間讀取記錄集
public static ListRecord readSet(Time t){
}
}
3.定義存取信息隊(duì)列的類
class MessageQueue{
//保存當(dāng)前時(shí)刻以后的所有信息的時(shí)間隊(duì)列,安順序
private syncronized static ListTime;
//插入隊(duì)列
public static void put(){
//需要按時(shí)間順序插入
}
//獲得當(dāng)前時(shí)間前的時(shí)間集
public static ListTime get(){
//獲得后需要將得到的時(shí)間從列表中刪除
}
}
4.編寫提醒類,用于提醒
class Reminder{
public void run(){
ListTime tl=getCurrentTime();
//查詢出所有
需要提醒的記錄調(diào)用remind()方法進(jìn)行提醒
}
//提醒
protected void remind(Record r){
//這里寫如何提醒
}
//獲得當(dāng)前時(shí)間
protected Time getCurrentTime(){
}
}
5.定時(shí)器類,
//提醒的主運(yùn)行類
class Main{
static Thread thread;
public Main(){
thread=new Thread(){
public void run(){
while(true){
new Reminder().run();
try{
Thread.sleep(60000);
}catch(Exception e ){}
}
}
}
public static void start(){
thread.start();
}
public sattic void stop(){
thread.stop();
}
}
}
只是個(gè)框架,具體代碼自己完成吧,可以查詢相關(guān)的API。
JAVA編程常用的軟件:
1、Eclipse:
Eclipse 是一個(gè)開放源代碼的、基于 Java 的可擴(kuò)展開發(fā)平臺。就其本身而言,它只是一個(gè)框架和一組服務(wù),用于通過插件組件構(gòu)建開發(fā)環(huán)境。幸運(yùn)的是,Eclipse 附帶了一個(gè)標(biāo)準(zhǔn)的插件集,包括 Java 開發(fā)工具(Java Development Tools,JDT)。
2、MyEclipse:
MyEclipse是Eclipse的升級版,也是一款功能強(qiáng)大的J2EE集成開發(fā)環(huán)境,由Genuitec公司發(fā)布,提供免費(fèi)版和收費(fèi)版。被譽(yù)為最好用的Java IDE之一。
MyEclipse 是對Eclipse IDE的擴(kuò)展,利用它可以在數(shù)據(jù)庫和JavaEE的開發(fā)、發(fā)布以及應(yīng)用程序服務(wù)器的整合方面極大的提高工作效率。
3、IntelliJ IDEA:
IntelliJ IDEA是一款綜合的Java 編程環(huán)境,被許多開發(fā)人員和行業(yè)專家譽(yù)為市場上最好用的IDE之一,與MyEclipse齊名。
它提供了一系列最實(shí)用的的工具組合:智能編碼輔助和自動控制,支持J2EE,Ant,JUnit和CVS集成,非平行的編碼檢查和創(chuàng)新的GUI設(shè)計(jì)器。
4、NetBeans:
NetBeans IDE是一個(gè)屢獲殊榮的集成開發(fā)環(huán)境,可以方便的在Windows、Mac、Linux和Solaris中運(yùn)行。NetBeans包括開源的開發(fā)環(huán)境和應(yīng)用平臺,NetBeans IDE可以使開發(fā)人員利用Java平臺能夠快速創(chuàng)建Web、企業(yè)、桌面以及移動的應(yīng)用程序。
5、BlueJ:
BlueJ是一款支持Java編程語言的集成開發(fā)環(huán)境(IDE)。它原本是為了教育目的而開發(fā)的,同時(shí)也適合于那些想做小型軟件開發(fā)的開發(fā)人員。它的運(yùn)行需要JDK(Java開發(fā)工具包)的幫助。BlueJ主要是為面向?qū)ο蟮某绦蛟O(shè)計(jì)教學(xué)而開發(fā)的,因此它的設(shè)計(jì)不同于其他的開發(fā)環(huán)境。
參考資料來源:百度百科-BlueJ
參考資料來源:百度百科-IntelliJ IDEA
參考資料來源:百度百科-Netbeans
參考資料來源:百度百科-eclipse
參考資料來源:百度百科-MyEclipse
一. 高亮的內(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í)才會被調(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í)對"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 true; }
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 {
// 這里就是對字符進(jìn)行著色
doc.setCharacterAttributes(pos, len, style, true);
} catch (Exception e) {}
}
}
七: 源碼
關(guān)鍵字著色的完成代碼如下, 可以直接編譯運(yùn)行. 對于數(shù)字, 運(yùn)算符, 字符串等的著色處理在以后的教程中會繼續(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;
}
}
}
/**
* 對單詞進(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é)束符, 不會拋出異常. 如果pos0, 則會拋出異常.
* 所以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 true; }
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 {
// 這里就是對字符進(jìn)行著色
doc.setCharacterAttributes(pos, len, style, true);
} catch (Exception e) {}
}
}
}
當(dāng)前文章:備忘錄編輯器java代碼,用java實(shí)現(xiàn)簡易備忘錄
網(wǎng)站URL:http://chinadenli.net/article41/dsegped.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、移動網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、全網(wǎng)營銷推廣、網(wǎng)站收錄、定制開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)