import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class StyleIntegrity {
JTextPane textPane;
public StyleIntegrity() {
System.setProperty("swing.aatext", "true");
String text = "This component models paragraphs that are composed of " +
"runs of character level attributes. Each paragraph may have a " +
"logical style attached to it which contains the default attributes " +
"to use if not overridden by attributes set on the paragraph or " +
"character run.";
textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
createStyles(doc);
setContent(doc, text);
styleContent(doc);
}
private void createStyles(StyledDocument doc) {
Style baseStyle = doc.addStyle("base", null);
StyleConstants.setFontFamily(baseStyle, "Lucida Sans Unicode");
StyleConstants.setFontSize(baseStyle, 18);
StyleConstants.setFirstLineIndent(baseStyle, 20f);
StyleConstants.setLeftIndent(baseStyle, 10f);
Style style = doc.addStyle("red", baseStyle);
StyleConstants.setForeground(style, Color.red);
}
private void setContent(StyledDocument doc, String text) {
try {
doc.insertString(0, text, doc.getStyle("base"));
} catch(BadLocationException e) {
System.out.printf("Bad location error: %s%n", e.getMessage());
}
}
private void styleContent(StyledDocument doc) {
Style style = doc.getStyle("base");
doc.setLogicalStyle(0, style);
style = doc.getStyle("red");
doc.setCharacterAttributes(116, 66, style, false);
}
private JMenuBar getMenuBar() {
JMenu edit = new JMenu("Edit");
edit.add(new DefaultEditorKit.CutAction());
edit.add(new DefaultEditorKit.CopyAction());
edit.add(new DefaultEditorKit.PasteAction());
edit.getItem(0).setText("cut");
edit.getItem(1).setText("copy");
edit.getItem(2).setText("paste");
JMenuBar menuBar = new JMenuBar();
menuBar.add(edit);
return menuBar;
}
private JScrollPane getContent() {
return new JScrollPane(textPane);
}
public static void main(String[] args) {
StyleIntegrity test = new StyleIntegrity();
JFrame f = new JFrame();
f.setJMenuBar(test.getMenuBar());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test.getContent());
f.setSize(500,400);
f.setLocation(200,200);
f.setVisible(true);
}
}