java的前景色是什么_java – JEditorPane为不同的单词设置前景色

我目前正在编写一个文本编辑器,我有这个代码,使特定单词的背景与其他单词不同,但我希望前景编辑颜色而不是背景.

这是我的代码:

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JEditorPane;

import javax.swing.JFrame;

import javax.swing.JTextPane;

import javax.swing.text.AbstractDocument;

import javax.swing.text.BadLocationException;

import javax.swing.text.DefaultHighlighter;

import javax.swing.text.Document;

import javax.swing.text.Highlighter;

import javax.swing.text.JTextComponent;

import javax.swing.text.MutableAttributeSet;

import javax.swing.text.SimpleAttributeSet;

import javax.swing.text.StyleConstants;

public class test {

final static JEditorPane jep = new JEditorPane();

static JButton button = new JButton("Refresh");

static JTextPane jTextPane1 = new JTextPane();

public static void main(String[] args) throws BadLocationException {

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jep.setText("Hello to the public place here are the public people");

frame.add(jep);

frame.pack();

frame.setSize(500, 500);

frame.add(button,BorderLayout.NORTH);

frame.setVisible(true);

button.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent arg0) {

try {

highlight(jep, "public");

} catch (BadLocationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

});

highlight(jep, "public");

}

public static void highlight(JTextComponent textComp, String pattern) throws BadLocationException {

try {

final MyHighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);

Highlighter hilite = textComp.getHighlighter();

MutableAttributeSet mas = (MutableAttributeSet)new SimpleAttributeSet ();

StyleConstants.setForeground(mas, Color.red);

Document doc = textComp.getDocument();

String text = doc.getText(0, doc.getLength());

int pos = 0;

// Search for pattern

while ((pos = text.indexOf(pattern, pos)) >= 0) {

hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);

pos += pattern.length();

}

}finally{

}

}

}

class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {

public MyHighlightPainter(Obect object) {

super((Color) object);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值