JTextPane multi-line to single-line conversion with HTML - java

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!

Related

how to get the content of a JTextPane with its styled format

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

Text Formatting is changed while Sharing data: Android

I want to share diamond detail in table format(Plain text not HTML)
I have made this using this library but its prints the data properly using the system.out but while I sharing it, its format is changed:
Below is my code:
List<String> headersList = Arrays.asList("", "");
List<List<String>> rowsList = Arrays.asList(
Arrays.asList("Stone Id :", details[0]),
Arrays.asList("Lab", details[1]),
Arrays.asList("Shape", details[2]),
Arrays.asList("Carat", details[3]),
Arrays.asList("Clarity-Color", details[4]),
Arrays.asList("Cut-Pol-Sym-Flou", details[5]));
Board board = new Board(75);
Table table = new Table(board, 75, headersList, rowsList);
table.invalidate().setGridMode(Table.GRID_NON).setRowsList(rowsList);
List<Integer> colWidthsList = Arrays.asList(30, 14);
table.setColWidthsList(colWidthsList);
Block tableBlock = table.tableToBlocks();
board.setInitialBlock(tableBlock);
board.build();
String preview1 = board.getPreview();
System.out.print(preview1);
sharingIntent.putExtra(Intent.EXTRA_TEXT,preview1);
The console uses monospaced font which takes exactly same width for all characters. But your view isn't using it, so it looks messed up.
Use a monospaced font.
Or use a tabular format. Perhaps a ListView with each row having two text views side by side having fixed width.

JLabel HTML New Line Issue

I'm trying to call a method from a class called Circle in my project which displays some basic information about the object in a JLabel. For some reason the text won't go to a new line even when I use HTML to try and format it:
#Override
public String toString(){
return "<html>Type: " + this.getClass().getSimpleName() + "<br>Radius: " + getRadius() + "<br>Area: " + df.format(getArea()) + "<br>Perimeter: </html>" + df.format(getPerimeter());
}
I'm trying to display the info with this code:
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnCalc && x==1){
//create object
double R = Double.parseDouble(Txt1.getText());
Circle circ = new Circle(R);
lblResult.setText(circ.toString());
}
When I run the program it just returns this:<html>Type: Circle<br>Radius: 4.0<br>Area: 50.27<br>Perimeter:</html> 25.13
edit: I tried just setting the text as an exception message instead of calling the method and it didn't work this way either
edit: Now this happens when I try to run the cylinder-sphere classes, but it doesn't do that when I don't have any html in the toString() method.
Turns out I was using a DecimalFormat in the last four classes which was what was giving me the exception. Once I got rid of that, the strings formatted nicely using a JTextPane instead of a JtextField.
From the image you pasted, it looks like it is a text INPUT control (under Show Info button), like JTextField and not a JLabel.
You can use HTML content with JLabel constructor as well as with its setText method too. It works fine.
JLabel lbl = new JLabel("<html>Type: Circle<br>Some info<br>More info</html>")
JLabel lbl2 = new JLabel();
lbl2.setText("<html>Type: Circle<br>Some info<br>More info</html>")
But if you want to have an INPUT control (as in your image), you can not use HTML with JTextField. You have to use JTextPane for this.
JTextPane txt = new JTextPane();
txt.setContentType("text/html");
txt.setText("<html>Type: Circle<br>Some info<br>More info</html>");

Set caret position on JScrollPane

I have a JEditoPane inside a JScrollPane. I have some text content that contain some pre-defined tokens. I'm storing the location of these tokens in the database.
When I set the text content into the JEditorPane, I embed the tokens with HTML. I also add HTML break lines to format the content.
Now problem comes when I want to scroll to one of the highlighted tokens. It seems that the start position of the tokens, which I stored in database, do not match when using the setCaretPosition(int). I know it's probably because my content in JEditorPane Document is mixed with HTML.
So is there a way to search for a String in the JEditorPane content, then somehow get the caret position where the string was found?
That's how you do it (ignore not using best practices ;) ) -
public static void main( String[] args ) {
final JEditorPane jEditorPane = new JEditorPane( "text/html", "<h1>This is some header</h1>After this text would be the CARRET<br>This is some more text<br>And more" );
final JScrollPane jScrollPane = new JScrollPane( jEditorPane );
final JFrame jframe = new JFrame( "HHHHHH" );
jframe.add( jScrollPane );
jframe.setSize( new Dimension( 200, 200 ) );
jframe.setVisible( true );
final String text = jEditorPane.getText();
final int index = text.indexOf( "T" );
jEditorPane.setCaretPosition( index + 1 );
while ( true ) {
try {
Thread.sleep( 1000000 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}
And that's the result:
You should store the result of indexof in the DB.
Do the strings have any commonalities? If they do, you could try using a combination of the java.util.scanner or/and java.util.regex.Matcher. Make sure to get the right regex for what you need. Once you have found a string get the indexOf the first letter and set the caret position to it.
Java Scanner
Java Matcher

How do I easily edit the style of the selected text in a JTextPane?

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.

Categories

Resources