CENTER align text when using StyledCellLabelProvider - java

I use a StyledCellLabelProvider to format text string as 'Hyperlink'.
// Column for the link
TableViewerColumn col2 = createTableViewerColumn("Link", 100, 1, viewer);
col2.setLabelProvider(new StyledCellLabelProvider() {
#Override
public void update(ViewerCell cell)
{
Object element = cell.getElement();
if(element instanceof Person)
{
Person person = (Person) cell.getElement();
/* make text look like a link */
StyledString text = new StyledString();
StyleRange myStyledRange = new StyleRange(0, person.getLocation().length(), Display.getCurrent().getSystemColor(SWT.COLOR_BLUE), null);
myStyledRange.underline = true;
text.append(person.getLocation(), StyledString.DECORATIONS_STYLER);
cell.setText(text.toString());
StyleRange[] range = { myStyledRange };
cell.setStyleRanges(range);
super.update(cell);
}
}
});
I also set text align of TableViewerColumn is CENTER but after using this style the text is left align.
How can I set CENTER align of text and change the cursor into link cursor when touch to the text?
Thanks

Related

Generate underline Waves itext7

How can I draw specific underline between :
String s = "This text is underlined with a dashed line";
Paragraph paragraph = new Paragraph();
Text text;
for (int i = 0; i <s.length() ; i++) {
text = new Text(String.valueOf(s.charAt(i)));
paragraph.add(text);
text.setNextRenderer(new DashedLineTextRenderer(text));
}
doc.add(paragraph);
doc.close();
private static class DashedLineTextRenderer extends TextRenderer {
public DashedLineTextRenderer(Text textElement) {
super(textElement);
}
// If renderer overflows on the next area, iText uses getNextRender() method to create a renderer for the overflow part.
// If getNextRenderer isn't overriden, the default method will be used and thus a default rather than custom
// renderer will be created
#Override
public IRenderer getNextRenderer() {
return new DashedLineTextRenderer((Text) modelElement);
}
#Override
public void draw(DrawContext drawContext) {
super.draw(drawContext);
Rectangle rect = this.getOccupiedAreaBBox();
PdfCanvas canvas = drawContext.getCanvas();
canvas.moveTo(rect.getLeft(), rect.getBottom());
canvas.curveTo(rect.getLeft()+100,rect.getBottom()+5,
rect.getLeft()+150,rect.getBottom()-2,rect.getLeft()+200,rect.getBottom()-5);
canvas.stroke();
}
}
if i do with single element text it works:
enter image description here
How i can define where draw canvas if there are several text elements
The question is underspecified (see clarifying comment). Basically to avoid the overlap as on the screenshot:
You can customize the renderer for the Paragraph, not for the Text:
private static class WaveUnderlinedParagraphRenderer extends ParagraphRenderer {
public WaveUnderlinedParagraphRenderer(Paragraph paragraph) {
super(paragraph);
}
#Override
public void draw(DrawContext drawContext) {
super.draw(drawContext);
Rectangle rect = this.getOccupiedAreaBBox();
PdfCanvas canvas = drawContext.getCanvas();
canvas.moveTo(rect.getLeft(), rect.getBottom());
canvas.curveTo(rect.getLeft() + 100, rect.getBottom() + 5,
rect.getLeft() + 150, rect.getBottom() - 2, rect.getLeft() + 200, rect.getBottom() - 5);
canvas.stroke();
}
#Override
public IRenderer getNextRenderer() {
return new WaveUnderlinedParagraphRenderer((Paragraph) modelElement);
}
}
Document doc = new Document(pdfDocument);
String s = "This text is underlined with a dashed line";
Paragraph paragraph = new Paragraph();
Text text;
for (int i = 0; i <s.length() ; i++) {
text = new Text(String.valueOf(s.charAt(i)));
paragraph.add(text);
}
paragraph.setNextRenderer(new WaveUnderlinedParagraphRenderer(paragraph));
doc.add(paragraph);
doc.close();
And get the following result:

How To Define Table's Vertical Alignment

Incredible easy question: I have a SWT table (viewer) and use a SWT.MeasureItem listener to set the cell height. How do I align the cell content to the bottom of the cell?
(It would probably work with another listener to SWT.PaintItem and some math and rendering all my cells manually, but that can't be the right way.)
public class TableDialog extends Dialog {
public static void main(String[] args) {
TableDialog dialog = new TableDialog(new Shell());
dialog.open();
}
public TableDialog(Shell parent) {
super(parent);
}
#Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Table Test");
newShell.setSize(500, 300);
}
#Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new FillLayout());
TableViewer viewer = new TableViewer(container, SWT.BORDER | SWT.FULL_SELECTION);
viewer.setContentProvider(new ArrayContentProvider());
viewer.setInput(Arrays.asList("A", "B", " C"));
Table table = viewer.getTable();
table.setLinesVisible(true);
table.addListener(SWT.MeasureItem, e -> e.height = 90);
return container;
}
}
Once you start using SWT.MeasureItem you need to do the drawing as well.
Since you are using TableViewer you can combine all this in one class by using an OwnerDrawLabelProvider as the viewer label provider. A very simple version would be something like this:
viewer.setLabelProvider(new OwnerDrawLabelProvider()
{
#Override
protected void paint(final Event event, final Object element)
{
String text = element.toString();
GC gc = event.gc;
int textHeight = gc.textExtent(text).y;
int yPos = event.y + event.height - textHeight;
gc.drawText(text, event.x, yPos);
}
#Override
protected void measure(final Event event, final Object element)
{
event.height = 90;
}
#Override
protected void erase(final Event event, final Object element)
{
// Stop the default draw of the foreground
event.detail &= ~SWT.FOREGROUND;
}
});
I am afraid, SWT.PaintItem is the right way in this case.
One of the SWT Snippets demonstrates how to draw multiple lines in a table item. It may serve as a starting point for your custom drawing code:
http://git.eclipse.org/c/platform/eclipse.platform.swt.git/tree/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet231.java
The Custom Drawing Table and Tree Items article provides further information.

Java Swing countrycombobox with icons

I hope someone can help me out. Iam trying to create a "countrycombobox" with icons in Java Swing. I found some stuff, but nothing did work for me. Maybe the problem is, that Iam still "new" to Java.
I just want it simple like this: http://www.zomex.com/libs/images/layout/whmcs-template-language-select-w-flags-eco.jpg
Just the flags in front of the countrys.
I would really appreciate a working example. I really wonder, that there is no standard option or a good code snippet(used Google a lot to find help here) for stuff like this.
I found a better example and wanna share my stuff with you. There is just one problem left, that I dont get it sized.
package view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CountryComboBox extends JPanel {
ImageIcon[] images;
String[] imgStrings = {"de"};
/*
* Despite its use of EmptyBorder, this panel makes a fine content
* pane because the empty border just increases the panel's size
* and is "painted" on top of the panel's normal background. In
* other words, the JPanel fills its entire background if it's
* opaque (which it is by default); adding a border doesn't change
* that.
*/
public CountryComboBox() {
super(new BorderLayout());
//Load the images and create an array of indexes.
images = new ImageIcon[imgStrings.length];
Integer[] intArray = new Integer[imgStrings.length];
for (int i = 0; i < imgStrings.length; i++) {
intArray[i] = new Integer(i);
images[i] = createImageIcon("/res/" + imgStrings[i] + ".png");
if (images[i] != null) {
images[i].setDescription(imgStrings[i]);
}
}
//Create the combo box.
JComboBox imgList = new JComboBox(intArray);
ComboBoxRenderer renderer= new ComboBoxRenderer();
imgList.setRenderer(renderer);
imgList.setMaximumRowCount(3);
//Lay out the demo.
add(imgList, BorderLayout.PAGE_START);
//setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = CountryComboBox.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
class ComboBoxRenderer extends JLabel
implements ListCellRenderer {
private Font uhOhFont;
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
}
/*
* This method finds the image and text corresponding
* to the selected value and returns the label, set up
* to display the text and image.
*/
#Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
int selectedIndex = ((Integer)value).intValue();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
//Set the icon and text. If icon was null, say so.
ImageIcon icon = images[selectedIndex];
String img = imgStrings[selectedIndex];
setIcon(icon);
if (icon != null) {
setText(img);
setFont(list.getFont());
} else {
setUhOhText(img + " (no image available)",
list.getFont());
}
return this;
}
//Set the font and text when no image was found.
protected void setUhOhText(String uhOhText, Font normalFont) {
if (uhOhFont == null) { //lazily create this font
uhOhFont = normalFont.deriveFont(Font.ITALIC);
}
setFont(uhOhFont);
setText(uhOhText);
}
}
}
I call it in a JPanel with absolute layout:
JComponent newContentPane = new CountryComboBox();
newContentPane.setOpaque(true); //content panes must be opaque
newContentPane.setBounds(10, 75, 50, 26);
contentPane.add(newContentPane);
setBounds isnt working, just to get the right position. I cant size it with this.
Best regards
Acanis

JGraph(T) graph element selection customization

I have as some problem with using JGraph(T) library.
I need change default selection view, example: default background is orange color, if vertex selected then green border was added, can i change this visualization strategy to change background to Color.BLUE on selected element.
I try execute follow code:
GraphSelectionModel graphSelectionModel = new DefaultGraphSelectionModel(jGraph);
graphSelectionModel.setSelectionMode(GraphSelectionModel.MULTIPLE_GRAPH_SELECTION);
graphSelectionModel.addGraphSelectionListener(new GraphSelectionListener()
{
HashMap oldestCellsAndAttrs = new HashMap();
#Override
public void valueChanged(GraphSelectionEvent e)
{
jGraph.getModel().beginUpdate();
m_jgAdapter.edit(oldestCellsAndAttrs, null, null, null);
oldestCellsAndAttrs.clear();
Map cellAndAttrs = new HashMap();
for (Object obj : e.getCells())
{
DefaultGraphCell cell = (DefaultGraphCell) obj;
oldestCellsAndAttrs.put(cell, JGraphModelAdapter.createDefaultVertexAttributes());
Map attrs = cell.getAttributes();
GraphConstants.setBackground(attrs, Color.BLUE);
cellAndAttrs.put(cell, attrs);
}
m_jgAdapter.edit(cellAndAttrs, null, null, null);
jGraph.getModel().endUpdate();
}
});
fillGraph(tree, g);
layout(g, m_jgAdapter, jGraph);
setSize(3 * width / 4, height);
jGraph.setSelectionModel(graphSelectionModel);
This change bkg on same selected objs, but not return after non-selection.
Is exists default solve for this problem ?
I solve problem with foollowing code:
#Override
public void valueChanged(GraphSelectionEvent e)
{
Object[] cells = e.getCells();
HashMap<DefaultGraphCell, AttributeMap> cellsAndAttrs = new HashMap<DefaultGraphCell, AttributeMap>();
for (Object c : cells)
{
DefaultGraphCell cell = (DefaultGraphCell) c;
AttributeMap cellAttrs = cell.getAttributes();
if (jGraph.isCellSelected(cell))
GraphConstants.setBackground(cellAttrs, SELECTED_COLOR);
else
GraphConstants.setBackground(cellAttrs, NON_SELECTED_COLOR);
cellsAndAttrs.put(cell, cellAttrs);
}
m_jgAdapter.edit(cellsAndAttrs, null, null, null);
}

How to add Hyperlink in SWT Table`s column?

How to add Hyperlink in SWT Table column ?
I`m using org.eclipse.swt.widgets.Table class.
Is there any way to do this without using TableViewer, JFace ?
I tried this way but not working correctly (not showing hyperlinks).
for(int i=2; i<4; i++){
Hyperlink link = new Hyperlink(table, SWT.WRAP);
link.setText(temp[i]);
link.setUnderlined(true);
TableEditor editor = new TableEditor(table);
editor.setEditor(link, tableItem[index-1], i); //set hyperlinks in column i
}
Below is one way to draw the hyperlink using TableView with a LabelProvider, as mentioned in Tonny Madsen's answer.
The code below just paints the hyperlink.
TableViewerColumn column = ...
column.setLabelProvider( new MyHyperlinkLabelProvider( tableViewerFiles.getTable() ));
private final class MyHyperlinkLabelProvider extends StyledCellLabelProvider {
MyHyperlink m_control;
private MyHyperlinkLabelProvider( Composite parent ) {
m_control = new MyHyperlink( parent, SWT.WRAP );
}
#Override
protected void paint( Event event, Object element ) {
String sValue = ... [Get cell value from row element]
m_control.setText( sValue );
GC gc = event.gc;
Rectangle cellRect = new Rectangle( event.x, event.y, event.width, event.height );
cellRect.width = 4000;
m_control.paintText( gc, cellRect);
}
}
private class MyHyperlink extends Hyperlink {
public MyHyperlink(Composite parent, int style) {
super(parent, style);
this.setUnderlined(true);
}
#Override
public void paintText(GC gc, Rectangle bounds) {
super.paintText(gc, bounds);
}
}
Yes, that is certainly possible. To do this you have to implement SWT.ItemPaint (and possibly also SWT.ItemErase and SWT.ItemMeassure).
It is easier with TableView though if you use the correct LabelProvider...
You need to set the size of the editor:
editor.grabHorizontal = true;
//or
editor.minimumWidth = 50;

Categories