Java Default Highlighter - java

Im using the DefaultHightlighter.DefaultHightlighterPainter to highlight text within a java text pane.
I want to remove all highlights (there could be more than one string highlighted) and want it to return the locations of the strings where the highlight has been removed, so obviously I cant use
pseudoCodeTextPane.getHighlighter().removeHighlight(highlight);
Can anyone help?
Thanks

How about something like
Highlighter.Highlight[] highlights = pseudoCodeTextPane.getHighlighter().getHighlights();
int[] startOffsets = new int[highlights.length];
int[] endOffsets = new int[highlights.length];
for (int i = 0; i < highlights.length; ++i) {
startOffsets[i] = highlights[i].getStartOffset();
endOffsets[i] = highlights[i].getEndOffset();
}
pseudoCodeTextPane.getHighlighter().removeAllHighlights();
// now do whatever processing you want to do with the highlight locations

If you remove all highlights (I suppose with removeAllHighlights) you can getHighlights before that and use the information you receive there.

Related

SWT/Jface cell text not getting saved in Model

I asked a question related to the issue I was having before, but a new one arose. Originally, I wanted the capability of highlighting a row in my table with a single click, and editing a cell with a double click. greg-449 gave me the solution to the problem (getting rid of the FocusCellManager and simply using EditingSupport along with the other classes I had, and setting the editorActivationStrategy to have the MOUSE_DOUBLE_CLICK_SELECTION bit. However, now when I type text into a cell, the text is not saved into my model. On the other hand, when I use the FocusCellManager, the text is indeed saved.
Now, I have to use CellEditors, as there is already a very long list of CellEditors set up for the specific columns. I am not sure if it is possible to use EditingSupport along with CellEditors, or if it necessary at all. I am attaching some snippets.
Relevant Section of DatumTableViewer.java:
FocusCellOwnerDrawHighlighter drawHighlighter = new FocusCellOwnerDrawHighlighter(this); //removed this to fix the highlighting issue
final TableViewerFocusCellManager mgr = new TableViewerFocusCellManager(this, drawHighlighter); //removed this to fix the highlighting issue.
final ColumnViewerEditorActivationStrategy editorActivationSupport = getEditorActivationStrategy();
int tableKeyboardTraversalFeature = getKeyboardTraversalFeature();
TableViewerEditor.create(this, mgr, editorActivationSupport, tableKeyboardActivationFeature);
DatumColumnEmnum[] tableColumnsAsArray = getTableColumnsAsArray();
createTable(this.getTable(), tableColumnsAsArray);
setColumnProperties(properties.getPresentedColumnNames); //properties is passed into constructor
setCellEditors(tableColumnsAsArray); //I think this doesn't work properly without FocusCellManager
DatumCellModifier modifier = new DatumCellModifier(this, properties, myExpressionDataProvider); // myExpressionDataProvider is passed into constructor)
setCellModifier(modifier);
setContentProvider(contentProvider);
setInput(_myDatumList); // myDatumList set before this snippet
}
setCellEditors:
private void setCellEditors(DatumColumnEnum[] columns)
{
cellEditor[] editors = new CellEditor[columns.length];
for(int i = 0; i < columns.length; i++){
DatumColumnEnum columnID = columns[i];
switch(columnID) // cases have been trimmed to shorten this snippet
{
case DATUM_ID_COLUMN:
case DATUM_NUMBER_COLUMN:
case DATUM_NAME_COLUMN:
editors[i] = new TextCellEditor(this.getTable());
((Text) editors[i].getControl()).setTextLimit(60);
break;
}
}
this.setCellEditors(editors);
}
I suspect these snippets contain the problem, but if not, then please let me know and I'll add the other functions as well.

How to add multiple lines in Label JavaFX

I have a problem that I don't really know how to add a multiple lines into Label in JavaFX.
For example:
Label label = new Label();
for(int i= 0; i<10; i++){
label.setText(Integer.toString(i));
}
So when the loop finishes, the label just only shows the final value which is 9.
So any solutions that can show all the numbers 1 - 9 with the break lines( such as '\n') between them.
This problem that happens when i want to show the Bill of my project that contain many dishes.
Thank you for your help.
You need to append and not set the text over and over again
AND you need the new line character '\n'
my suggestion would be like using a variable to append the information and when you are done with that step, then set the label.text
Example:
StringBuilder msg = new StringBuilder():
Label label = new Label();
for (int i = 0; i < 10; i++) {
msg.append(Integer.toString(i));
msg.append(",\n"); //this is the new line you need
}
label.setText(msg.toString());

Text editor in NetBeans

I am trying to implement a text editor in NetBeans with simple functions like: text styling (bold, italic, underlined ...), open file, save file and search. Search function searches for a specified string in the document and highlights the results. The problem occurs when I am trying to remove those highlights or add new ones for different search. Currently I use StyledDocument object together with jTextPane.
private void textHighlight(int startAt, int endAt, Color c) {
Style sCh;
sCh = textEditor.addStyle("TextBackground", null);
StyleConstants.setBackground(sCh, c);
StyledDocument sDoc = textEditor.getStyledDocument();
sDoc.setCharacterAttributes(startAt, endAt - startAt, sCh, false);
}
private void textFind(java.awt.event.ActionEvent evt) {
int searchIndex = 0;
String searchValue = searchField.getText();
if(lastIndex != -1) {
while(searchIndex < lastIndex) {
countOccurencies++;
int i = textEditor.getText().indexOf(searchValue, searchIndex);
textHighlight(i, i+searchValue.length(), Color.MAGENTA);
searchIndex = i+searchValue.length();
}
statusLabel.setText(countOccurencies + " rezultatov.");
} else {
statusLabel.setText("Ni rezultatov!");
}
}
}
private void searchEnd(java.awt.event.ActionEvent evt) {
textEditor.removeStyle("TextBackground");
}
removeStyle() doesn't seem to be working.
Must admit I don't know how Styles work, but maybe the attributes of the Style are copied to the Document at the time you add the Style?
Another option is to use the Highlighter class. See textPane.getHighlighter(). Then you can keep track of the individual highlights you add in an ArrayList and then use the ArrayList to remove the highlights when you want the clear the text pan.
Also, inside your search loop you have a couple of problems:
Don't use the getText() method. This can cause problems with text offsets being off by one for every line of text in the text pane. See Text and New Lines for more information and the solution.
You are getting the text inside the loop which is not very efficient. You should only get the text once outside the loop.

Which text margin does SWT Table use when drawing text?

I got a relatively easy question - but I cannot find anything anywhere to answer it.
I use a simple SWT table widget in my application that displays only text in the cells. I got an incremental search feature and want to highlight text snippets in all cells if they match.
So when typing "a", all "a"s should be highlighted.
To get this, I add an SWT.EraseItem listener to interfere with the background drawing. If the current cell's text contains the search string, I find the positions and calculate relative x-coordinates within the text using event.gc.stringExtent - easy.
With that I just draw rectangles "behind" the occurrences.
Now, there's a flaw in this. The table does not draw the text without a margin, so my x coordinate does not really match - it is slightly off by a few pixels! But how many?? Where do I retrieve the cell's text margins that table's own drawing will use? No clue. Cannot find anything.
Bonus question: the table's draw method also shortens text and adds "..." if it does not fit into the cell. Hmm. My occurrence finder takes the TableItem's text and thus also tries to mark occurrences that are actually not visible because they are consumed by the "...".
How do I get the shortened text and not the "real" text within the EraseItem draw handler?
#Override
public void handleEvent( final Event event ) {
final TableItem ti = (TableItem) event.item;
final int index = event.index;
final GC gc = event.gc;
if( ti == null || currentSwyt.isEmpty() ) {
return;
}
final String text = ti.getText( index );
if( !text.contains( currentSwyt ) ) {
return;
}
// search text is contained
final String[] parts = text.split( currentSwyt );
final int swytWidth = gc.stringExtent( currentSwyt ).x;
// calculate positions, must be relative to the text's start
int x = event.x; // THIS IS THE PROBLEM: event.x is not enough!
final int[] pos = new int[parts.length - 1];
for( int i = 0; i < parts.length - 1; i++ ) {
x += gc.stringExtent( parts[i] ).x;
pos[i] = x;
}
final Color red = event.display.getSystemColor( SWT.COLOR_RED );
final Color oldBackground = gc.getBackground();
gc.setBackground( red );
for( int j = 0; j < pos.length; j++ ) {
gc.fillRectangle( pos[j], event.y, swytWidth, event.height );
}
gc.setBackground( oldBackground );
event.detail &= ~SWT.BACKGROUND;
}
I think it would be quite useful for you to have a look at TableViewer and StyledCellLabelProvider. That will make your task a lot easier I think considering the kind of text formatting you require. Since the drawing is than completely handled by the label provider, you can avoid these pesky margin issues.
As for almost all SWT Widgets, this might be OS dependent. The actual "drawing" of the table is done using OS resources.
However, it might be worth having a look at TableItem#getTextBounds(int).
It returns a Rectangle that should reflect the margins.
For your bonus question: I have never seen the text being shortened automatically in my applications. In fact I had a hard time doing this myself. But that might as well be OS dependent, since I use Linux.

JOptionPane in Java

Does anyone know why tab (\t) does not work with JOptionPane.showMessageDialog?
My code is as follows:
String addText = "NAME\t\tADDRESS\t\tTEL.No\tEMAIL\n";
for (int i = 0; i < addressBookSize; i++) {
addText = addText+entry[i].viewAllInfo();
}
System.out.print(addText);
JOptionPane.showMessageDialog(null, addText);
Are there other ways to align text in JOptionPane?
Put your tabbed text into JTextArea
String addText = "NAME\t\tADDRESS\t\tTEL.No\tEMAIL\n";
for (int i = 0; i < addressBookSize; i++) {
addText = addText+entry[i].viewAllInfo();
}
System.out.print(addText);
JOptionPane.showMessageDialog(null, new JTextArea(addText));
Looking at your data again, I'd probably display it in a JTable, and then if desired, would display this in a JOptionPane or in a GUI. If you need simpler, then display it in a JTextArea whose font has been set to monospaced, and use String.format(...) or something similar to allow your Strings to be displayed in a table.

Categories

Resources