I have a JTextPane, and I would like to output text in it using StyledDocument. Here is my StyledDocument object:
StyledDocument dox = (StyledDocument) textArea.getDocument();
Style style = dox.addStyle("StyleName", null);
StyleConstants.setFontFamily(style, Font.SANS_SERIF);
StyleConstants.setFontSize(style, 8);
dox.insertString(dox.getLength(), "<b>Some Text</b>", null);
The problem right now is if I edit the text with html code, it does not display the way I want. I want the text to be displayed as bolded instead of literally <b>Some Text</b>.
Is there a way to do this?
I did figure it out on my own in the end using HTMLEditorKit, here's the answer for futher reference
StyledDocument dox = (StyledDocument) textArea.getDocument();
textPane.setEditorKit(new HTMLEditorKit());
textPane.setText("<b>Some Text</b>");
Related
I am trying to make a simple word processor that edits the text to make it bold, italic, underline, background color and foreground color. The problem is I want to set the contents/text of the JTextPane with all its edited attributes to a single object to save it to another class as a data field which have other data fields like date created and the name of the document given by the user.
I think the best approach its using html as content type for the Text Pane and string builders.
for example,
TextPane tp = new JTextPane();
tp.setContentType("text/html");
StringBuilder sb = new StringBuilder();
sb.append("<span style=\"color:red\">" + Hello red + "</span>");
sb.append("<span style=\"color:blue\">" + Hello blue + "</span>");
...
tp.setText(sb); // will print text with the style
works the same in the other way,
String txt = tp.getText();
System.print(txt); //wil show html code
You can reference http://www.java2s.com/Tutorials/Java/Swing_How_to/JTextPane/Style_JTextPane_with_HTML_and_CSS.htm
I it possible to align the text inside a JTextArea to the right (or change the text alignment in general)?
|Left |
| Centered |
| Right| <- Like this
I've been searching for hours and it seems others have asked this question before but there are no good answers (that actually work).
Thanks in advance!
Try with JEditorPane or JTextPane instead of JTextArea.
Please have a look at my another post JEditorPane vertical aligment for complete sample code.
For more info have a look at this thread Vertical Alignment of Text in JEditorPane
Sample code:
JTextPane output = new JTextPane();
SimpleAttributeSet attribs = new SimpleAttributeSet();
StyleConstants.setAlignment(attribs, StyleConstants.ALIGN_RIGHT);
output.setParagraphAttributes(attribs, true);
EDIT
You can try
JTextArea jTextArea = new JTextArea();
jTextArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
Read more about How to set the orientation of JTextArea from right to left
You have to use JTextPane, It's better than JTextArea on this case:
try this code:
JTextPane textPane=new JTextPane();
StyledDocument style = textPane.getStyledDocument();
SimpleAttributeSet align= new SimpleAttributeSet();
StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);
style.setParagraphAttributes(0, style.getLength(), align, false);
modify this code If You want to make the text:
+in the Right :
StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);
+in the Center :
StyleConstants.setAlignment(align, StyleConstants.ALIGN_CENTER);
+in the Left :
StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT);
Take a look at this Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment
I have a piece in my code that formats a string, appends html/css tags and then adds the text to a JTextPane. I create the textPane in some panel's constructor with the following:
public PnlSmartCommands(ServerLogFormatter formatter, ServerCommandsComponent container){
setLayout( new java.awt.BorderLayout() );
this.container = container;
txtServerCommands = new JTextPane();
txtServerCommands.setContentType("text/html");
scpServerCommands = new JScrollPane( );
this.formatter = formatter;
scpServerCommands.setViewportView( txtServerCommands );
scpServerCommands.getVerticalScrollBar().setUnitIncrement(16);
scpServerCommands.getHorizontalScrollBar().setUnitIncrement(50);
add( scpServerCommands, java.awt.BorderLayout.CENTER );
txtServerCommands.setEditable(false);
loadRules(txtServerCommands);
and I add text to the pane with a formatting function that takes all previous requests from an ArrayList, deletes all found HTML tags, formats it and then adds new HTML and BODY tags, and then use .setText(String arg0) to set the text to a JTextPane.
public String formatMemoryString(){
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<body>");
for(int i=0;i<logMemoryHolder.size(); i++){
sb.append(logMemoryHolder.get(i));
if(!(i==logMemoryHolder.size())){
sb.append("<br>");
}
}
sb.append("</body>");
sb.append("</html>");
return sb.toString();
Now here's the problem - the response is always fit into the box over multiple lines, not on a single line. While this is actually good, I need to add functionality to span it over a single line. ! http://i.stack.imgur.com/zy4yC.jpg - this is what it looks like currently. I would like to add a checkbox that formats the value as a single line, or allows the textPane to do so. Any idea how I go about doing that? The HTML that I put into the pane is as follows : http://www.upload.ee/files/3501071/testHtml.html.html
Thanks in advance!
relatively self-explaining, How can i center selected text in a JTextPane?
(Aligning Any text is helpful)
Found some code on coderanch:
SimpleAttributeSet attribs = new SimpleAttributeSet();
StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_CENTER);
pane.setParagraphAttributes(attribs,true);
How do I easily edit the style of the selected text in a JTextPane? There doesn't seem to be many resources on this. Even if you can direct me to a good resource on this, I'd greatly appreciate it.
Also, how do I get the current style of the selected text? I tried styledDoc.getLogicalStyle(textPane.getSelectionStart()); but it doesn't seem to be working.
Here's a code snippet to insert a formatted "Hello World!" string in a JEditorPane:
Document doc = yourEditorPane.getDocument();
StyleContext sc = new StyleContext();
Style style = sc.addStyle("yourStyle", null);
Font font = new Font("Arial", Font.BOLD, 18);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setFontFamily(style, font.getFamily());
StyleConstants.setBold(style, true);
doc.insertString(doc.getLength(), "Hello World!", style);
Take a look at the following code in this pastebin:
http://pbin.oogly.co.uk/listings/viewlistingdetail/d6fe483a52c52aa951ca15762ed3d3
The example is from here:
http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneStylesExample3.htm
It looks like you can change the style using the following in an action listener:
final Style boldStyle = sc.addStyle("MainStyle", defaultStyle);
StyleConstants.setBold(boldStyle, true);
doc.setCharacterAttributes(0, 10, boldStyle, true);
It sets the style of the text between the given offset and length to a specific style.
See the full pastebin for more details. That should fix your problem though.
The easiest way to manipulate text panels is using editor kits and their associated actions. You can find a demo of this in the JDK samples (under jdk\demo\jfc\Stylepad).
Sample code that installs a StyledEditorKit and uses a FontSizeAction to manipulate the text:
public static void main(String[] args) {
// create a rich text pane
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// install the editor kit
StyledEditorKit editorKit = new StyledEditorKit();
textPane.setEditorKit(editorKit);
// build the menu
JMenu fontMenu = new JMenu("Font Size");
for (int i = 48; i >= 8; i -= 10) {
JMenuItem menuItem = new JMenuItem("" + i);
// add an action
menuItem
.addActionListener(new StyledEditorKit.FontSizeAction(
"myaction-" + i, i));
fontMenu.add(menuItem);
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(fontMenu);
// show in a frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setJMenuBar(menuBar);
frame.setContentPane(scrollPane);
frame.setVisible(true);
}
(Tip: if you want to use a FontFamilyAction, have a look at GraphicsEnvironment.getAvailableFontFamilyNames() and logical font family names.)
I'd recommend taking a look at Sun's Java Tutorial about editor panes.
Ok, wow. Hard question. So I have not found a way to get the style of a given character. You can, however, get the MutableAttributeSet for a given character and then test to see if the style is in that attribute set.
Style s; //your style
Element run = styledDocument.getCharacterElement(
textPane.getSelectionStart() );
MutableAttributeSet curAttr =
( MutableAttributeSet )run.getAttributes();
boolean containsIt = curAttr.containsAttributes( s );
One problem with getting the Style for a range of characters is that there may be more than one style applied to that range (example: you may select text where some is bold and some is not).
To update the selected text you can:
Style s; //your style
JTextPane textPane; //your textpane
textPane.setCharacterAttributes( s, false );
Oh, and it appears that the function getLogicalStyle doesn't work because it's returning the default style (or maybe just the style) for the paragraph that contains p, rather than the the style of the character at p.