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
Related
I'm trying to get original values from MyTextField
try {
MaskFormatter mf1 = new MaskFormatter("##/##/##");
MyTextField.setFormatterFactory(new DefaultFormatterFactory(mf1));
}
//input 123456
//System.out.println(MyTextField.getValue());
//display 12/34/56
With MyTextField.getText() and MyTextField.getValue() , I always get "12/34/56".
Is there any way to get the original value (123456) from MyTextField ?
Remove the undesired characters with MyTextField.getValue().replace("/", "");
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.
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!
I have a dialog, within the dialog there is a tableviewer thats shows the results from user actions. I have created a method that has a print button. The print code include is sample code I have found from examples.
final Text t = new Text(composite, SWT.BORDER | SWT.MULTI);
Button localPrintersButton = new Button(composite, SWT.PUSH);
localPrintersButton.setText("Print Results");
localPrintersButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PrintDialog printDialog = new PrintDialog(Display.getCurrent().getActiveShell(), SWT.NONE);
printDialog.setText("Print");
PrinterData printerData = printDialog.open( );
if(!(printerData==null))
{
Printer p = new Printer(printerData);
p.startJob("PrintJob");
p.startPage( );
Rectangle trim = p.computeTrim(0, 0, 0, 0);
Point dpi = p.getDPI( );
int leftMargin = dpi.x + trim.x;
int topMargin = dpi.y / 2 + trim.y;
GC gc = new GC(p);
Font font = gc.getFont( );
String printText= t.getText( );
Point extent = gc.stringExtent(printText);
gc.drawString(printText, leftMargin, topMargin +
font.getFontData( )[0].getHeight( ));
p.endPage( );
gc.dispose( );
p.endJob( );
p.dispose( );
}
}
});
When my dialog opens there is a text box next to the print button. I can type something in the text box, select the print button and select my local printer, then it prints the contents of the text box.
I am trying to figure out how to print out the table instead of the textbox
Is this possible?
I think you are looking for
Control.class
public boolean print (GC gc)
Perhaps you can create a GC from the Table widget and use GC#copyArea(Image, int, int) to create an image of the table to print.
If the table has scroll bars and not all data is visible, you might need to do some extra work to create multiple images and stitch them together. Hope this helps.
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.