JTextPane textPane = new JTextPane(); // Makes text red Style style = textPane.addStyle("Red", null); StyleConstants.setForeground(style, Color.red); // Inherits from "Red"; makes text red and underlined style = textPane.addStyle("Red Underline", style); StyleConstants.setUnderline(style, true); // Makes text 24pts style = textPane.addStyle("24pts", null); StyleConstants.setFontSize(style, 24); // Makes text 12pts style = textPane.addStyle("12pts", null); StyleConstants.setFontSize(style, 12); // Makes text italicized style = textPane.addStyle("Italics", null); StyleConstants.setItalic(style, true); // Makes text bold style = textPane.addStyle("Bold", null); StyleConstants.setBold(style, true); JTextPane c = textPane; // Construct a sorted list of style names DefaultStyledDocument doc = (DefaultStyledDocument)textPane.getDocument(); java.util.List l = new ArrayList(); Enumeration enum = doc.getStyleNames(); while (enum.hasMoreElements()) { l.add(enum.nextElement()); } Collections.sort(l); // First sub menu applies character attributes final JPopupMenu menu = new JPopupMenu(); JMenu submenu = new JMenu("Character"); for (int i=0; i<l.size(); i++) { submenu.add(new JMenuItem(new DoStyleAction((String)l.get(i), CHARACTER))); } menu.add(submenu); // Second sub menu applies paragraph attributes submenu = new JMenu("Paragraph"); for (int i=0; i<l.size(); i++) { submenu.add(new JMenuItem(new DoStyleAction((String)l.get(i), PARAGRAPH))); } menu.add(submenu); // Third submenu applies logical attributes submenu = new JMenu("Logical"); for (int i=0; i<l.size(); i++) { submenu.add(new JMenuItem(new DoStyleAction((String)l.get(i), LOGICAL))); } menu.add(submenu); // Add a listener to display pop-up textPane.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { menu.show(evt.getComponent(), evt.getX(), evt.getY()); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { menu.show(evt.getComponent(), evt.getX(), evt.getY()); } } }); static final int CHARACTER = 1; static final int PARAGRAPH = 2; static final int LOGICAL = 3; // Assumes the style name is the same as the action name. // The type specifies how the style should be applied. // The style is applied to the text within the selection. public static class DoStyleAction extends StyledEditorKit.StyledTextAction { int type; public DoStyleAction(String styleName, int type) { super(styleName); this.type = type; } public void actionPerformed(ActionEvent e) { JTextPane c = (JTextPane)getEditor(e); if (c != null) { String styleName = e.getActionCommand(); StyledDocument doc = (StyledDocument)c.getDocument(); switch (type) { case CHARACTER: c.setCharacterAttributes(doc.getStyle(styleName), true); break; case PARAGRAPH: c.setParagraphAttributes(doc.getStyle(styleName), true); break; case LOGICAL: c.setLogicalStyle(doc.getStyle(styleName)); break; } } } }