Java Tutorial/Swing/JTextPane
Содержание
- 1 Adding Icon to JTextPane
- 2 A separation of a data from the visual representation.
- 3 A style can have multiple attributes; this one makes text bold and italic
- 4 Background color
- 5 Change the Font size of JTextPane
- 6 Create a center-aligned tab stop at 300 pixels from the left margin
- 7 Create a decimal-aligned tab stop at 400 pixels from the left margin
- 8 Create a right-aligned tab stop at 200 pixels from the left margin
- 9 Create a tab set from the tab stops
- 10 Customizing Tab Stops in a JTextPane Component
- 11 Determine if the attribute is a color or a font-related attribute.
- 12 Determining If a Style Attribute Applies to a Character or the Paragraph
- 13 Difference between JEditorPane and JTextPane
- 14 Displaying Simple HTML Files
- 15 Duplicate style
- 16 Editor based on JTextPane
- 17 Enumerating the Paragraphs of a JTextPane Component
- 18 Font family
- 19 Foreground color
- 20 Get logical style and restore it after new paragraph style
- 21 Inserting a Component into a JTextPane Component
- 22 Inserting an Image into a JTextPane Component
- 23 Inserting Styled Text in a JTextPane Component
- 24 Italicize the entire paragraph containing the position 12
- 25 JTextPane Look and Feel
- 26 Listing the Attributes in a Style
- 27 Listing the Styles Associated with a JTextPane
- 28 Loading a JTextPane with Content: using StyleConstants to set Align, Font size, Space
- 29 Replace style
- 30 Set logical style; replaces paragraph style"s parent
- 31 Setting the Font and Color of Text in a JTextPane Using Styles: Inherits from Red; makes text red and underlined
- 32 Setting the Font and Color of Text in a JTextPane Using Styles: Makes text 24pts
- 33 Setting the Font and Color of Text in a JTextPane Using Styles: Makes text italicized
- 34 Setting the Font and Color of Text in a JTextPane Using Styles: Makes text red
- 35 Sharing Styles Between JTextPanes
- 36 SimpleAttribute: Bold, Italic
- 37 SimpleAttribute: Bold, Italic, Color
- 38 StyleConstants Class
- 39 TabStop and TabSet Classes
- 40 Uses a listener label to display caret and selection status For JTextPane
- 41 Using Actions with Text Components: JTextPane
Adding Icon to JTextPane
import java.awt.BorderLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class JTextPaneWithIcon {
public static void main(String args[]) {
JFrame frame = new JFrame("TextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyleContext context = new StyleContext();
StyledDocument document = new DefaultStyledDocument(context);
Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);
Icon icon = new ImageIcon("yourFile.gif");
JLabel label = new JLabel(icon);
StyleConstants.setComponent(labelStyle, label);
try {
document.insertString(document.getLength(), "Ignored", labelStyle);
} catch (BadLocationException badLocationException) {
System.err.println("Oops");
}
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
A separation of a data from the visual representation.
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);
}
}
A style can have multiple attributes; this one makes text bold and italic
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// A style can have multiple attributes; this one makes text bold and italic
Style style = textPane.addStyle("Bold Italic", null);
StyleConstants.setBold(style, true);
StyleConstants.setItalic(style, true);
}
}
Background color
public class Main{
public static void main(String[] argv){
// Get the text pane"s document
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument)textPane.getDocument();
// Create a style object and then set the style attributes
Style style = doc.addStyle("StyleName", null);
StyleConstants.setBackground(style, Color.blue);
// Append to document
doc.insertString(doc.getLength(), "Some Text", style);
} }
Change the Font size of JTextPane
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception{
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
// Create a style object and then set the style attributes
Style style = doc.addStyle("StyleName", null);
StyleConstants.setFontSize(style, 30);
doc.insertString(doc.getLength(), "Some Text", style);
}
}
Create a center-aligned tab stop at 300 pixels from the left margin
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.TabStop;
public class Main {
public static void main(String[] argv) {
List list = new ArrayList();
int pos = 300;
int align = TabStop.ALIGN_CENTER;
int leader = TabStop.LEAD_NONE;
TabStop tstop = new TabStop(pos, align, leader);
list.add(tstop);
}
}
Create a decimal-aligned tab stop at 400 pixels from the left margin
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextPane;
import javax.swing.text.TabStop;
public class Main {
public static void main(String[] argv) {
// Create a text pane
JTextPane textPane = new JTextPane();
List list = new ArrayList();
int pos = 400;
int align = TabStop.ALIGN_DECIMAL;
int leader = TabStop.LEAD_NONE;
TabStop tstop = new TabStop(pos, align, leader);
list.add(tstop);
}
}
Create a right-aligned tab stop at 200 pixels from the left margin
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.TabStop;
public class Main {
public static void main(String[] argv) {
List list = new ArrayList();
int pos = 200;
int align = TabStop.ALIGN_RIGHT;
int leader = TabStop.LEAD_NONE;
TabStop tstop = new TabStop(pos, align, leader);
list.add(tstop);
}
}
Create a tab set from the tab stops
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;
public class Main {
public static void main(String[] argv) {
JTextPane textPane = new JTextPane();
List list = new ArrayList();
TabStop[] tstops = (TabStop[]) list.toArray(new TabStop[0]);
TabSet tabs = new TabSet(tstops);
Style style = textPane.getLogicalStyle();
StyleConstants.setTabSet(style, tabs);
textPane.setLogicalStyle(style);
}
}
Customizing Tab Stops in a JTextPane Component
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextPane;
import javax.swing.text.TabStop;
public class Main {
public static void main(String[] argv) {
List list = new ArrayList();
// Create a left-aligned tab stop at 100 pixels from the left margin
float pos = 100;
int align = TabStop.ALIGN_LEFT;
int leader = TabStop.LEAD_NONE;
TabStop tstop = new TabStop(pos, align, leader);
list.add(tstop);
}
}
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleConstants;
public class Main {
public static void main(String[] argv) {
// Check if color-based attribute
boolean b = StyleConstants.Foreground instanceof AttributeSet.ColorAttribute;
b = StyleConstants.Italic instanceof AttributeSet.ColorAttribute;
// Check if font-based attribute
b = StyleConstants.Italic instanceof AttributeSet.FontAttribute;
b = StyleConstants.Foreground instanceof AttributeSet.FontAttribute;
}
}
Determining If a Style Attribute Applies to a Character or the Paragraph
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleConstants;
public class Main {
public static void main(String[] argv) {
// Check if character-based attribute
boolean b = StyleConstants.Italic instanceof AttributeSet.CharacterAttribute;
b = StyleConstants.LineSpacing instanceof AttributeSet.CharacterAttribute;
// Check if paragraph-based attribute
b = StyleConstants.LineSpacing instanceof AttributeSet.ParagraphAttribute;
b = StyleConstants.Italic instanceof AttributeSet.ParagraphAttribute;
}
}
Difference between JEditorPane and JTextPane
The JTextPane is a specialized form of the JEditorPane designed especially for the editing (and display) of styled text.
Displaying Simple HTML Files
import java.awt.BorderLayout;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception{
String url = "http://java.sun.ru";
JEditorPane editorPane = new JEditorPane(url);
editorPane.setEditable(false);
JFrame frame = new JFrame();
frame.getContentPane().add(editorPane, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Duplicate style
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Set text in the range [5, 7) red
doc.setCharacterAttributes(5, 2, textPane.getStyle("Red"), true);
}
}
Editor based on JTextPane
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
public class MainClass {
public MainClass() {
JFrame frame = new JFrame();
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
JPanel north = new JPanel();
JMenuBar menu = new JMenuBar();
JMenu styleMenu = new JMenu();
styleMenu.setText("Style");
Action boldAction = new BoldAction();
boldAction.putValue(Action.NAME, "Bold");
styleMenu.add(boldAction);
Action italicAction = new ItalicAction();
italicAction.putValue(Action.NAME, "Italic");
styleMenu.add(italicAction);
Action foregroundAction = new ForegroundAction();
foregroundAction.putValue(Action.NAME, "Color");
styleMenu.add(foregroundAction);
Action formatTextAction = new FontAndSizeAction();
formatTextAction.putValue(Action.NAME, "Font and Size");
styleMenu.add(formatTextAction);
menu.add(styleMenu);
north.add(menu);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(north, BorderLayout.NORTH);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(800, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new MainClass();
}
}
class BoldAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = 9174670038684056758L;
public BoldAction() {
super("font-bold");
}
public String toString() {
return "Bold";
}
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean bold = (StyleConstants.isBold(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setBold(sas, bold);
setCharacterAttributes(editor, sas, false);
}
}
}
class ItalicAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = -1428340091100055456L;
public ItalicAction() {
super("font-italic");
}
public String toString() {
return "Italic";
}
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean italic = (StyleConstants.isItalic(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setItalic(sas, italic);
setCharacterAttributes(editor, sas, false);
}
}
}
class ForegroundAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = 6384632651737400352L;
JColorChooser colorChooser = new JColorChooser();
JDialog dialog = new JDialog();
boolean noChange = false;
boolean cancelled = false;
public ForegroundAction() {
super("foreground");
}
public void actionPerformed(ActionEvent e) {
JTextPane editor = (JTextPane) getEditor(e);
if (editor == null) {
JOptionPane.showMessageDialog(null,
"You need to select the editor pane before you can change the color.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
int p0 = editor.getSelectionStart();
StyledDocument doc = getStyledDocument(editor);
Element paragraph = doc.getCharacterElement(p0);
AttributeSet as = paragraph.getAttributes();
fg = StyleConstants.getForeground(as);
if (fg == null) {
fg = Color.BLACK;
}
colorChooser.setColor(fg);
JButton accept = new JButton("OK");
accept.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
fg = colorChooser.getColor();
dialog.dispose();
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cancelled = true;
dialog.dispose();
}
});
JButton none = new JButton("None");
none.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
noChange = true;
dialog.dispose();
}
});
JPanel buttons = new JPanel();
buttons.add(accept);
buttons.add(none);
buttons.add(cancel);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(colorChooser, BorderLayout.CENTER);
dialog.getContentPane().add(buttons, BorderLayout.SOUTH);
dialog.setModal(true);
dialog.pack();
dialog.setVisible(true);
if (!cancelled) {
MutableAttributeSet attr = null;
if (editor != null) {
if (fg != null && !noChange) {
attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, fg);
setCharacterAttributes(editor, attr, false);
}
}
}// end if color != null
noChange = false;
cancelled = false;
}
private Color fg;
}
class FontAndSizeAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = 584531387732416339L;
private String family;
private float fontSize;
JDialog formatText;
private boolean accept = false;
JComboBox fontFamilyChooser;
JComboBox fontSizeChooser;
public FontAndSizeAction() {
super("Font and Size");
}
public String toString() {
return "Font and Size";
}
public void actionPerformed(ActionEvent e) {
JTextPane editor = (JTextPane) getEditor(e);
int p0 = editor.getSelectionStart();
StyledDocument doc = getStyledDocument(editor);
Element paragraph = doc.getCharacterElement(p0);
AttributeSet as = paragraph.getAttributes();
family = StyleConstants.getFontFamily(as);
fontSize = StyleConstants.getFontSize(as);
formatText = new JDialog(new JFrame(), "Font and Size", true);
formatText.getContentPane().setLayout(new BorderLayout());
JPanel choosers = new JPanel();
choosers.setLayout(new GridLayout(2, 1));
JPanel fontFamilyPanel = new JPanel();
fontFamilyPanel.add(new JLabel("Font"));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = ge.getAvailableFontFamilyNames();
fontFamilyChooser = new JComboBox();
for (int i = 0; i < fontNames.length; i++) {
fontFamilyChooser.addItem(fontNames[i]);
}
fontFamilyChooser.setSelectedItem(family);
fontFamilyPanel.add(fontFamilyChooser);
choosers.add(fontFamilyPanel);
JPanel fontSizePanel = new JPanel();
fontSizePanel.add(new JLabel("Size"));
fontSizeChooser = new JComboBox();
fontSizeChooser.setEditable(true);
fontSizeChooser.addItem(new Float(4));
fontSizeChooser.addItem(new Float(8));
fontSizeChooser.addItem(new Float(12));
fontSizeChooser.addItem(new Float(16));
fontSizeChooser.addItem(new Float(20));
fontSizeChooser.addItem(new Float(24));
fontSizeChooser.setSelectedItem(new Float(fontSize));
fontSizePanel.add(fontSizeChooser);
choosers.add(fontSizePanel);
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
accept = true;
formatText.dispose();
family = (String) fontFamilyChooser.getSelectedItem();
fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString());
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
formatText.dispose();
}
});
JPanel buttons = new JPanel();
buttons.add(ok);
buttons.add(cancel);
formatText.getContentPane().add(choosers, BorderLayout.CENTER);
formatText.getContentPane().add(buttons, BorderLayout.SOUTH);
formatText.pack();
formatText.setVisible(true);
MutableAttributeSet attr = null;
if (editor != null && accept) {
attr = new SimpleAttributeSet();
StyleConstants.setFontFamily(attr, family);
StyleConstants.setFontSize(attr, (int) fontSize);
setCharacterAttributes(editor, attr, false);
}
}
}
Enumerating the Paragraphs of a JTextPane Component
import javax.swing.JTextPane;
import javax.swing.text.Element;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
Element section = textPane.getDocument().getDefaultRootElement();
int paraCount = section.getElementCount();
for (int i = 0; i < paraCount; i++) {
Element e = section.getElement(i);
int rangeStart = e.getStartOffset();
int rangeEnd = e.getEndOffset();
String para = textPane.getText(rangeStart, rangeEnd - rangeStart);
System.out.println(para);
}
}
}
Font family
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setFontFamily(style, "SansSerif");
// Append to document
doc.insertString(doc.getLength(), "Some Text", style);
}
}
Foreground color
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception{
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
// Create a style object and then set the style attributes
Style style = doc.addStyle("StyleName", null);
StyleConstants.setForeground(style, Color.white);
// Append to document
doc.insertString(doc.getLength(), "Some Text", style);
}
}
Get logical style and restore it after new paragraph style
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
Style style = textPane.addStyle(null, null);
StyleConstants.setForeground(style, Color.red);
textPane.setLogicalStyle(style);
Style logicalStyle = textPane.getLogicalStyle();
style = textPane.addStyle(null, null);
StyleConstants.setBold(style, true);
textPane.setParagraphAttributes(style, true);
textPane.setLogicalStyle(logicalStyle);
}
}
Inserting a Component into a JTextPane Component
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setComponent(style, new JButton("OK"));
doc.insertString(doc.getLength(), "ignored text", style);
}
}
Inserting an Image into a JTextPane Component
import javax.swing.ImageIcon;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception{
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon("imagefile"));
doc.insertString(doc.getLength(), "ignored text", style);
}
}
Inserting Styled Text in a JTextPane Component
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception{
JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setItalic(style, true);
doc.insertString(doc.getLength(), "Some Text", style);
}
}
Italicize the entire paragraph containing the position 12
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Italicize the entire paragraph containing the position 12
doc.setParagraphAttributes(12, 1, textPane.getStyle("Italic"), true);
}
}
JTextPane Look and Feel
Property StringObject TypeTextPane.actionMapActionMapTextPane.backgroundColorTextPane.borderBorderTextPane.caretAspectRatioNumberTextPane.caretBlinkRateIntegerTextPane.caretForegroundColorTextPane.focusInputMapInputMapTextPane.fontFontTextPane.foregroundColorTextPane.inactiveForegroundColorTextPane.keyBindingsKeyBinding[ ]TextPane.marginInsetsTextPane.selectionBackgroundColorTextPane.selectionForegroundColorTextPaneUIString
Listing the Attributes in a Style
import java.util.Enumeration;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
DefaultStyledDocument doc = (DefaultStyledDocument) textPane.getDocument();
Enumeration e1 = doc.getStyleNames();
while (e1.hasMoreElements()) {
String styleName = (String) e1.nextElement();
System.out.println(styleName);
Style style = doc.getStyle(styleName);
int count = style.getAttributeCount();
System.out.println(count);
Enumeration e = style.getAttributeNames();
while (e.hasMoreElements()) {
Object o = e.nextElement();
if (o instanceof String) {
String attrName = (String) o;
Object attrValue = style.getAttribute(attrName);
System.out.println(attrValue);
} else if (o == StyleConstants.NameAttribute) {
styleName = (String) style.getAttribute(o);
System.out.println(styleName);
} else if (o == StyleConstants.ResolveAttribute) {
Style parent = (Style) style.getAttribute(o);
System.out.println(parent.getName());
} else {
String attrName = o.toString();
System.out.println(attrName);
Object attrValue = style.getAttribute(o);
System.out.println(attrValue);
}
}
}
}
}
Listing the Styles Associated with a JTextPane
import java.util.Enumeration;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
DefaultStyledDocument doc = (DefaultStyledDocument) textPane.getDocument();
Enumeration e = doc.getStyleNames();
while (e.hasMoreElements()) {
String styleName = (String) e.nextElement();
System.out.println(styleName);
Style style = doc.getStyle(styleName);
}
}
}
Loading a JTextPane with Content: using StyleConstants to set Align, Font size, Space
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class JTextPaneStyle {
private static String message = "public class JTextPaneStyle" +
"public static void main(String args[]) {" +
"JFrame frame = new JFrame();";
public static void main(String args[]) {
JFrame frame = new JFrame("TextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyleContext context = new StyleContext();
StyledDocument document = new DefaultStyledDocument(context);
Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
try {
document.insertString(document.getLength(), message, style);
} catch (BadLocationException badLocationException) {
System.err.println("Oops");
}
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Replace style
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
Style style = textPane.addStyle(null, null);
StyleConstants.setForeground(style, Color.red);
textPane.setLogicalStyle(style);
// Set paragraph style; removes logical style
style = textPane.addStyle(null, null);
StyleConstants.setUnderline(style, true);
textPane.setParagraphAttributes(style, true);
// paragraph is now underlined, not red
}
}
Set logical style; replaces paragraph style"s parent
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
Style style = textPane.addStyle(null, null);
StyleConstants.setForeground(style, Color.red);
textPane.setLogicalStyle(style);
style = textPane.addStyle(null, null);
StyleConstants.setForeground(style, Color.red);
textPane.setLogicalStyle(style);
}
}
Setting the Font and Color of Text in a JTextPane Using Styles: Inherits from Red; makes text red and underlined
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
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);
}
}
Setting the Font and Color of Text in a JTextPane Using Styles: Makes text 24pts
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Makes text 24pts
Style style = textPane.addStyle("24pts", null);
StyleConstants.setFontSize(style, 24);
}
}
Setting the Font and Color of Text in a JTextPane Using Styles: Makes text italicized
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Makes text italicized
Style style = textPane.addStyle("Italic", null);
StyleConstants.setItalic(style, true);
}
}
Setting the Font and Color of Text in a JTextPane Using Styles: Makes text red
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Makes text red
Style style = textPane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.red);
}
}
Sharing Styles Between JTextPanes
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class Main {
public static void main(String[] argv) throws Exception {
JTextPane c1 = new JTextPane();
JTextPane c2 = new JTextPane();
StyleContext styleContext = new StyleContext();
c1.setDocument(new DefaultStyledDocument(styleContext));
c2.setDocument(new DefaultStyledDocument(styleContext));
Style style = c1.addStyle("style name", null);
StyleConstants.setForeground(style, Color.red);
style = c2.getStyle("style name");
StyleConstants.setBold(style, true);
}
}
SimpleAttribute: Bold, Italic
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class SimpleAttributeBoldItalic {
public static void main(String args[]) {
JFrame frame = new JFrame("Simple Attributes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyledDocument document = new DefaultStyledDocument();
SimpleAttributeSet attributes = new SimpleAttributeSet();
attributes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
attributes.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);
try {
document.insertString(document.getLength(), "Bold, Italic", attributes);
} catch (BadLocationException badLocationException) {
System.err.println("Bad insert");
}
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
SimpleAttribute: Bold, Italic, Color
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class SimpleAttributeBoldItalicColor {
public static void main(String args[]) {
JFrame frame = new JFrame("Simple Attributes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyledDocument document = new DefaultStyledDocument();
SimpleAttributeSet attributes = new SimpleAttributeSet();
attributes = new SimpleAttributeSet();
attributes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.FALSE);
attributes.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.FALSE);
attributes.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.LIGHT_GRAY);
try {
document.insertString(document.getLength(), " Bold, Italic and light gray color", attributes);
} catch (BadLocationException badLocationException) {
System.err.println("Bad insert");
}
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
StyleConstants Class
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class SimpleAttributeBoldItalicColor {
public static void main(String args[]) {
JFrame frame = new JFrame("Simple Attributes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyledDocument document = new DefaultStyledDocument();
SimpleAttributeSet attributes = new SimpleAttributeSet();
attributes = new SimpleAttributeSet();
attributes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.FALSE);
attributes.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.FALSE);
attributes.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.LIGHT_GRAY);
try {
document.insertString(document.getLength(), " Bold, Italic and light gray color", attributes);
} catch (BadLocationException badLocationException) {
System.err.println("Bad insert");
}
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
TabStop and TabSet Classes
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;
public class TabSample {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame("Tab Attributes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyledDocument document = new DefaultStyledDocument();
//TabStop.ALIGN_CENTER, TabStop.ALIGN_DECIMAL,TabStop.ALIGN_LEFT, TabStop.ALIGN_RIGHT
//"\tBAR\n", "\tCENTER\n", "\t3.14159265\n", "\tLEFT\n", "\tRIGHT\n" };
SimpleAttributeSet attributes = new SimpleAttributeSet();
TabStop tabstop = new TabStop(150, TabStop.ALIGN_BAR, TabStop.LEAD_DOTS);
int position = document.getLength();
document.insertString(position, "TabStop.ALIGN_BAR", null);
TabSet tabset = new TabSet(new TabStop[] { tabstop });
StyleConstants.setTabSet(attributes, tabset);
document.setParagraphAttributes(position, 1, attributes, false);
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Uses a listener label to display caret and selection status For JTextPane
/*
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
public class TextComponentDemo extends JFrame {
JTextPane textPane;
AbstractDocument doc;
static final int MAX_CHARACTERS = 300;
JTextArea changeLog;
String newline = "\n";
HashMap<Object, Action> actions;
// undo helpers
protected UndoAction undoAction;
protected RedoAction redoAction;
protected UndoManager undo = new UndoManager();
public TextComponentDemo() {
super("TextComponentDemo");
// Create the text pane and configure it.
textPane = new JTextPane();
textPane.setCaretPosition(0);
textPane.setMargin(new Insets(5, 5, 5, 5));
StyledDocument styledDoc = textPane.getStyledDocument();
if (styledDoc instanceof AbstractDocument) {
doc = (AbstractDocument) styledDoc;
//doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));
} else {
System.err.println("Text pane"s document isn"t an AbstractDocument!");
System.exit(-1);
}
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(200, 200));
// Create the text area for the status log and configure it.
changeLog = new JTextArea(5, 30);
changeLog.setEditable(false);
JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
// Create a split pane for the change log and the text area.
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scrollPane, scrollPaneForLog);
splitPane.setOneTouchExpandable(true);
// Create the status area.
JPanel statusPane = new JPanel(new GridLayout(1, 1));
CaretListenerLabel caretListenerLabel = new CaretListenerLabel("Caret Status");
statusPane.add(caretListenerLabel);
// Add the components.
getContentPane().add(splitPane, BorderLayout.CENTER);
getContentPane().add(statusPane, BorderLayout.PAGE_END);
// Set up the menu bar.
createActionTable(textPane);
JMenu editMenu = createEditMenu();
JMenu styleMenu = createStyleMenu();
JMenuBar mb = new JMenuBar();
mb.add(editMenu);
mb.add(styleMenu);
setJMenuBar(mb);
// Add some key bindings.
addBindings();
// Put the initial text into the text pane.
initDocument();
// Start watching for undoable edits and caret changes.
doc.addUndoableEditListener(new MyUndoableEditListener());
textPane.addCaretListener(caretListenerLabel);
doc.addDocumentListener(new MyDocumentListener());
}
// This listens for and reports caret movements.
protected class CaretListenerLabel extends JLabel implements CaretListener {
public CaretListenerLabel(String label) {
super(label);
}
// Might not be invoked from the event dispatching thread.
public void caretUpdate(CaretEvent e) {
displaySelectionInfo(e.getDot(), e.getMark());
}
protected void displaySelectionInfo(final int dot, final int mark) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (dot == mark) { // no selection
try {
Rectangle caretCoords = textPane.modelToView(dot);
// Convert it to view coordinates.
setText("caret: text position: " + dot + ", view location = [" + caretCoords.x + ", "
+ caretCoords.y + "]" + newline);
} catch (BadLocationException ble) {
setText("caret: text position: " + dot + newline);
}
} else if (dot < mark) {
setText("selection from: " + dot + " to " + mark + newline);
} else {
setText("selection from: " + mark + " to " + dot + newline);
}
}
});
}
}
// This one listens for edits that can be undone.
protected class MyUndoableEditListener implements UndoableEditListener {
public void undoableEditHappened(UndoableEditEvent e) {
// Remember the edit and update the menus.
undo.addEdit(e.getEdit());
undoAction.updateUndoState();
redoAction.updateRedoState();
}
}
// And this one listens for any changes to the document.
protected class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
displayEditInfo(e);
}
public void removeUpdate(DocumentEvent e) {
displayEditInfo(e);
}
public void changedUpdate(DocumentEvent e) {
displayEditInfo(e);
}
private void displayEditInfo(DocumentEvent e) {
Document document = (Document) e.getDocument();
int changeLength = e.getLength();
changeLog.append(e.getType().toString() + ": " + changeLength + " character"
+ ((changeLength == 1) ? ". " : "s. ") + " Text length = " + document.getLength() + "."
+ newline);
}
}
// Add a couple of emacs key bindings for navigation.
protected void addBindings() {
InputMap inputMap = textPane.getInputMap();
// Ctrl-b to go backward one character
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.backwardAction);
// Ctrl-f to go forward one character
key = KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.forwardAction);
// Ctrl-p to go up one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.upAction);
// Ctrl-n to go down one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.downAction);
}
// Create the edit menu.
protected JMenu createEditMenu() {
JMenu menu = new JMenu("Edit");
// Undo and redo are actions of our own creation.
undoAction = new UndoAction();
menu.add(undoAction);
redoAction = new RedoAction();
menu.add(redoAction);
menu.addSeparator();
// These actions come from the default editor kit.
// Get the ones we want and stick them in the menu.
menu.add(getActionByName(DefaultEditorKit.cutAction));
menu.add(getActionByName(DefaultEditorKit.copyAction));
menu.add(getActionByName(DefaultEditorKit.pasteAction));
menu.addSeparator();
menu.add(getActionByName(DefaultEditorKit.selectAllAction));
return menu;
}
// Create the style menu.
protected JMenu createStyleMenu() {
JMenu menu = new JMenu("Style");
Action action = new StyledEditorKit.BoldAction();
action.putValue(Action.NAME, "Bold");
menu.add(action);
action = new StyledEditorKit.ItalicAction();
action.putValue(Action.NAME, "Italic");
menu.add(action);
action = new StyledEditorKit.UnderlineAction();
action.putValue(Action.NAME, "Underline");
menu.add(action);
menu.addSeparator();
menu.add(new StyledEditorKit.FontSizeAction("12", 12));
menu.add(new StyledEditorKit.FontSizeAction("14", 14));
menu.add(new StyledEditorKit.FontSizeAction("18", 18));
menu.addSeparator();
menu.add(new StyledEditorKit.FontFamilyAction("Serif", "Serif"));
menu.add(new StyledEditorKit.FontFamilyAction("SansSerif", "SansSerif"));
menu.addSeparator();
menu.add(new StyledEditorKit.ForegroundAction("Red", Color.red));
menu.add(new StyledEditorKit.ForegroundAction("Green", Color.green));
menu.add(new StyledEditorKit.ForegroundAction("Blue", Color.blue));
menu.add(new StyledEditorKit.ForegroundAction("Black", Color.black));
return menu;
}
protected void initDocument() {
String initString[] = { "Use the mouse to place the caret.",
"Use the edit menu to cut, copy, paste, and select text.",
"Also to undo and redo changes.", "Use the style menu to change the style of the text.",
"Use these emacs key bindings to move the caret:", "ctrl-f, ctrl-b, ctrl-n, ctrl-p." };
SimpleAttributeSet[] attrs = initAttributes(initString.length);
try {
for (int i = 0; i < initString.length; i++) {
doc.insertString(doc.getLength(), initString[i] + newline, attrs[i]);
}
} catch (BadLocationException ble) {
System.err.println("Couldn"t insert initial text.");
}
}
protected SimpleAttributeSet[] initAttributes(int length) {
// Hard-code some attributes.
SimpleAttributeSet[] attrs = new SimpleAttributeSet[length];
attrs[0] = new SimpleAttributeSet();
StyleConstants.setFontFamily(attrs[0], "SansSerif");
StyleConstants.setFontSize(attrs[0], 16);
attrs[1] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setBold(attrs[1], true);
attrs[2] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setItalic(attrs[2], true);
attrs[3] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setFontSize(attrs[3], 20);
attrs[4] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setFontSize(attrs[4], 12);
attrs[5] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setForeground(attrs[5], Color.red);
return attrs;
}
// The following two methods allow us to find an
// action provided by the editor kit by its name.
private void createActionTable(JTextComponent textComponent) {
actions = new HashMap<Object, Action>();
Action[] actionsArray = textComponent.getActions();
for (int i = 0; i < actionsArray.length; i++) {
Action a = actionsArray[i];
actions.put(a.getValue(Action.NAME), a);
}
}
private Action getActionByName(String name) {
return actions.get(name);
}
class UndoAction extends AbstractAction {
public UndoAction() {
super("Undo");
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.undo();
} catch (CannotUndoException ex) {
System.out.println("Unable to undo: " + ex);
ex.printStackTrace();
}
updateUndoState();
redoAction.updateRedoState();
}
protected void updateUndoState() {
if (undo.canUndo()) {
setEnabled(true);
putValue(Action.NAME, undo.getUndoPresentationName());
} else {
setEnabled(false);
putValue(Action.NAME, "Undo");
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.redo();
} catch (CannotRedoException ex) {
System.out.println("Unable to redo: " + ex);
ex.printStackTrace();
}
updateRedoState();
undoAction.updateUndoState();
}
protected void updateRedoState() {
if (undo.canRedo()) {
setEnabled(true);
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
setEnabled(false);
putValue(Action.NAME, "Redo");
}
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
final TextComponentDemo frame = new TextComponentDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Display the window.
frame.pack();
frame.setVisible(true);
}
// The standard main method.
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Using Actions with Text Components: JTextPane
import java.util.Arrays;
import java.util.ruparator;
import javax.swing.Action;
import javax.swing.JTextPane;
import javax.swing.text.JTextComponent;
public class ListActionsJTextPane {
public static void main(String args[]) {
JTextComponent component = new JTextPane();
// Process action list
Action actions[] = component.getActions();
// Define comparator to sort actions
Comparator<Action> comparator = new Comparator<Action>() {
public int compare(Action a1, Action a2) {
String firstName = (String) a1.getValue(Action.NAME);
String secondName = (String) a2.getValue(Action.NAME);
return firstName.rupareTo(secondName);
}
};
Arrays.sort(actions, comparator);
int count = actions.length;
System.out.println("Count: " + count);
for (int i = 0; i < count; i++) {
System.out.printf("%28s : %s\n",actions[i].getValue(Action.NAME),actions[i].getClass().getName());
}
}
}
Count: 71 beep : javax.swing.text.DefaultEditorKit$BeepAction caret-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-begin : javax.swing.text.DefaultEditorKit$BeginAction caret-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction caret-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction caret-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction caret-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-end : javax.swing.text.DefaultEditorKit$EndAction caret-end-line : javax.swing.text.DefaultEditorKit$EndLineAction caret-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction caret-end-word : javax.swing.text.DefaultEditorKit$EndWordAction caret-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-next-word : javax.swing.text.DefaultEditorKit$NextWordAction caret-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction caret-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction center-justify : javax.swing.text.StyledEditorKit$AlignmentAction copy-to-clipboard : javax.swing.text.DefaultEditorKit$CopyAction cut-to-clipboard : javax.swing.text.DefaultEditorKit$CutAction default-typed : javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction delete-next : javax.swing.text.DefaultEditorKit$DeleteNextCharAction delete-previous : javax.swing.text.DefaultEditorKit$DeletePrevCharAction dump-model : javax.swing.text.DefaultEditorKit$DumpModelAction font-bold : javax.swing.text.StyledEditorKit$BoldAction font-family-Monospaced : javax.swing.text.StyledEditorKit$FontFamilyAction font-family-SansSerif : javax.swing.text.StyledEditorKit$FontFamilyAction font-family-Serif : javax.swing.text.StyledEditorKit$FontFamilyAction font-italic : javax.swing.text.StyledEditorKit$ItalicAction font-size-10 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-12 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-14 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-16 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-18 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-24 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-36 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-48 : javax.swing.text.StyledEditorKit$FontSizeAction font-size-8 : javax.swing.text.StyledEditorKit$FontSizeAction font-underline : javax.swing.text.StyledEditorKit$UnderlineAction insert-break : javax.swing.text.StyledEditorKit$StyledInsertBreakAction insert-content : javax.swing.text.DefaultEditorKit$InsertContentAction insert-tab : javax.swing.text.DefaultEditorKit$InsertTabAction left-justify : javax.swing.text.StyledEditorKit$AlignmentAction page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction paste-from-clipboard : javax.swing.text.DefaultEditorKit$PasteAction right-justify : javax.swing.text.StyledEditorKit$AlignmentAction select-all : javax.swing.text.DefaultEditorKit$SelectAllAction select-line : javax.swing.text.DefaultEditorKit$SelectLineAction select-paragraph : javax.swing.text.DefaultEditorKit$SelectParagraphAction select-word : javax.swing.text.DefaultEditorKit$SelectWordAction selection-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-begin : javax.swing.text.DefaultEditorKit$BeginAction selection-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction selection-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction selection-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction selection-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-end : javax.swing.text.DefaultEditorKit$EndAction selection-end-line : javax.swing.text.DefaultEditorKit$EndLineAction selection-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction selection-end-word : javax.swing.text.DefaultEditorKit$EndWordAction selection-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-next-word : javax.swing.text.DefaultEditorKit$NextWordAction selection-page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction selection-page-left : javax.swing.text.DefaultEditorKit$PageAction selection-page-right : javax.swing.text.DefaultEditorKit$PageAction selection-page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction selection-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction selection-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction set-read-only : javax.swing.text.DefaultEditorKit$ReadOnlyAction set-writable : javax.swing.text.DefaultEditorKit$WritableAction toggle-componentOrientation : javax.swing.text.DefaultEditorKit$ToggleComponentOrientationAction unselect : javax.swing.text.DefaultEditorKit$UnselectAction