Java tutorial
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.JToolBar; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; public class DocumentModel { public static void main(String[] args) { final StyledDocument doc; final JTextPane textpane; JFrame f = new JFrame(); f.setTitle("Document Model"); JToolBar toolbar = new JToolBar(); JButton boldb = new JButton("bold"); JButton italb = new JButton("italic"); JButton strib = new JButton("strike"); JButton undeb = new JButton("underline"); toolbar.add(boldb); toolbar.add(italb); toolbar.add(strib); toolbar.add(undeb); f.add(toolbar, BorderLayout.NORTH); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); JScrollPane pane = new JScrollPane(); textpane = new JTextPane(); textpane.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); doc = textpane.getStyledDocument(); Style style = textpane.addStyle("Bold", null); StyleConstants.setBold(style, true); style = textpane.addStyle("Italic", null); StyleConstants.setItalic(style, true); style = textpane.addStyle("Underline", null); StyleConstants.setUnderline(style, true); style = textpane.addStyle("Strike", null); StyleConstants.setStrikeThrough(style, true); boldb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc.setCharacterAttributes(textpane.getSelectionStart(), textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Bold"), false); } }); italb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc.setCharacterAttributes(textpane.getSelectionStart(), textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Italic"), false); } }); strib.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc.setCharacterAttributes(textpane.getSelectionStart(), textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Strike"), false); } }); undeb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc.setCharacterAttributes(textpane.getSelectionStart(), textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Underline"), false); } }); pane.getViewport().add(textpane); panel.add(pane); f.add(panel); f.setSize(new Dimension(380, 320)); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }