import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;


public class TextEditTest extends JFrame {
	private DefaultStyledDocument doc;

	public TextEditTest(){
		super("TextEditTest");

		doc = new DefaultStyledDocument();
		JTextPane text = new JTextPane();
		text.setDocument(doc);
		text.setText("hello world");

		// highlight first word
		doc.setCharacterAttributes(0,5,createLabelAttribute("hello"),true);

		JButton button = new JButton("Action");
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				try{
					String text= doc.getText(0,11);
					doc.setCharacterAttributes(6,11,createLabelAttribute("world"),true);
	
				}catch(BadLocationException ex){
					ex.printStackTrace();
				}
			}	
		});

		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(text,BorderLayout.CENTER);
		getContentPane().add(button,BorderLayout.SOUTH);
		pack();
	}	

	private AttributeSet createLabelAttribute(String text){

		JLabel lbl = new JLabel(text);
		lbl.setToolTipText("This is the reason to put a label here");
		lbl.setAlignmentY(.8f);
		lbl.setMaximumSize(lbl.getPreferredSize());
		lbl.setForeground(Color.red);


		// add create attr set
		SimpleAttributeSet attr = new SimpleAttributeSet();
		StyleConstants.setComponent(attr,lbl);
		//StyleConstants.setBold(attr,true);

		return attr;
	}	



	public static void main(String [] args){
		(new TextEditTest()).setVisible(true);
	}
}

