How to draw some figures on a editor with draw2d in a eclipse RCP? - eclipse-plugin

I mean drawing somg simple shape like circle,rectangleFigure,and polylineConnectistrong.It seems that a LightweightSystem has to been constructed on a Canvas such as a Shell.And in a RCP application when I add an extension of an editor,the editor extends org.eclipse.ui.part.EditorPart by default.It has a method called createPartControl.This method has a parameter (Composite parent).
So I write the following code and it give me a Unhandled event loop exception
public void createPartControl(Composite parent) {
Shell shell = parent.getShell();
shell.open();
Display display = shell.getDisplay();
LightweightSystem lws = new LightweightSystem(shell);
IFigure panel = new Figure();
lws.setContents(panel);
RectangleFigure node1 = new RectangleFigure();
RectangleFigure node2 = new RectangleFigure();
node1.setBackgroundColor(ColorConstants.red);
node1.setBounds(new Rectangle(30, 30, 64, 36));
node2.setBackgroundColor(ColorConstants.blue);
node2.setBounds(new Rectangle(100, 100, 64, 36));
PolylineConnection conn = new PolylineConnection();
conn.setSourceAnchor(new ChopboxAnchor(node1));
conn.setTargetAnchor(new ChopboxAnchor(node2));
conn.setTargetDecoration(new PolygonDecoration());
Label label = new Label("Midpoint");
label.setOpaque(true);
label.setBackgroundColor(ColorConstants.buttonLightest);
label.setBorder(new LineBorder());
conn.add(label, new MidpointLocator(conn, 0));
panel.add(node1);
panel.add(node2);
panel.add(conn);
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ())
display.sleep ();
}
}
So how to solve this problem and how to draw these figures on the editor?

As you want to draw inside the editor, you don't need to create new Shell nor dispatch events from the event queue as you would do in a standalone SWT application; just create a Canvas and draw into it. This should help you:
public void createPartControl(Composite parent) {
Canvas canvas = new Canvas(parent, SWT.NONE);
LightweightSystem lws = new LightweightSystem(canvas);
IFigure panel = new Figure();
lws.setContents(panel);
[...]
panel.add(node1);
panel.add(node2);
panel.add(conn);
}

Related

The problem with the layout of checkbox when using BooleanFieldEditor

I am trying to use BooleanFieldEditor instead of Button with style SWT.CHECK. And I am getting the problem with layout of the checkbox.
The significant part of my previous code is:
Composite projectGroup = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
projectGroup.setLayout(layout);
projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Button checkBox = new Button(projectGroup, SWT.CHECK);
checkBox.setText(Messages.getString("WizardNewProjectCreationPage.createEmptyProject")); //$NON-NLS-1$
checkBox.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent event) {
Button button = (Button) event.getSource();
shouldEmptyProjectBeCreated = button.getSelection();
}
});
It gives me this result:
In this case the checkbox has a small indent at the top and the left side.
The significant part of my current code is:
Composite projectGroup = new Composite(parent, SWT.NONE);
GridLayoutFactory.fillDefaults().extendedMargins(100, 0, 100, 0).spacing(100, 100).applyTo(projectGroup);
BooleanFieldEditor emptyProjectCheckbox = new BooleanFieldEditor("createEmptyProject",
Messages.getString("WizardNewProjectCreationPage.createEmptyProject"), projectGroup);
// GridDataFactory.defaultsFor(projectGroup).grab(true, false).span(2, 1).applyTo(projectGroup);
// emptyProjectCheckbox.fillIntoGrid(projectGroup, 1);
createEmptyProject = emptyProjectCheckbox.getBooleanValue();
Whatever values I set into extendedMargins() and spacing() methods, the result is the same - checkbox is located strictly at the level of the upper frame:
As you can see, in this case indents are smaller than on the first picture. I want to make the same indents as on the first image and want to understand, how to manage the location of BooleanFieldEditor's checkbox relatively to another elements.
Using second composite solves the problem:
Composite projectGroup = new Composite(parent, SWT.NONE);
GridLayoutFactory.fillDefaults().extendedMargins(5, 0, 5, 0).applyTo(projectGroup);
//intermediate composite, which needs to work around the problem with layout of checkbox of BooleanFieldEditor
Composite intermediateComposite = new Composite(projectGroup, SWT.NONE);
BooleanFieldEditor emptyProjectCheckbox = new BooleanFieldEditor("createEmptyProject",
Messages.getString("WizardNewProjectCreationPage.createEmptyProject"), intermediateComposite);
createEmptyProject = emptyProjectCheckbox.getBooleanValue();

Codename One Drag & Drop blackens dialog background

I'm developing an app that uses drag & drop operations. The drag & drop part includes four containers as drop targets and two draggable labels.
The app works as expected in the simulator, but when I install it on my Android phone, the background of the dialog (otherwise white) turns black for a swift moment as soon as the draggable components (labels) are released (then gets back to the original light color).
In the theme builder, I have set the background of the dialog to an almost white color (unselected, selected, pressed, disabled), but that doesn't show any effect.
Is there any turnaround to keep the background color stable? Any help would be appreciated.
Here is the relevant code excerpt:
Dialog dialog_W1 = new Dialog();
dialog_W1.setScrollableY(true);
dialog_W1.setLayout(new BoxLayout(2));
dialog_W1.setScrollableY(true);
dialog_W1.setTitle("Acerte o bichinho");
Image img_Cat = Image.createImage("/cat.png");
ScaleImageLabel label_Scaled_Image = new ScaleImageLabel(img_Cat);
label_Scaled_Image.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);
label_Scaled_Image.setUIID("NewLabel");
Label label_1 = new Label("ga");
Label label_2 = new Label("to");
label_1.setUIID("LabelWord");
label_2.setUIID("LabelWord");
label_1.setDraggable(true);
label_2.setDraggable(true);
Container c_1 = new Container();
Container c_2 = new Container();
Container c_3 = new Container();
Container c_4 = new Container();
c_1.setDropTarget(true);
c_2.setDropTarget(true);
c_3.setDropTarget(true);
c_4.setDropTarget(true);
c_1.setLayout(new BoxLayout(2));
c_2.setLayout(new BoxLayout(2));
c_3.setLayout(new BoxLayout(2));
c_4.setLayout(new BoxLayout(2));
c_1.setUIID("Container_1");
c_2.setUIID("Container_1");
c_3.setUIID("Container_2");
c_4.setUIID("Container_2");
c_3.add(label_2);
c_4.add(label_1);
GridLayout gl = new GridLayout(2,2);
Container container_0 = new Container(gl);
container_0.add(c_1);
container_0.add(c_2);
container_0.add(c_3);
container_0.add(c_4);
ArrayList <Container> list_Containers = new ArrayList<>();
list_Containers.add(c_1);
list_Containers.add(c_2);
list_Containers.add(c_3);
list_Containers.add(c_4);
ArrayList <Label> list_Labels = new ArrayList<>();
list_Labels.add(label_1);
list_Labels.add(label_2);
for (Label label : list_Labels) {
label.addDragOverListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Container c : list_Containers) {
int int_C = c.getComponentCount();
if (int_C == 1) {
c.setDropTarget(false);
} else if (int_C == 0) {
c.setDropTarget(true);
}
}
}
});
}
I suggest showing the Dialog as a modless dialog instead of using the show method use showModless() or similar.
Odd things like this can happen because of the EDT nesting inherent in modal dialogs, normally we don't recommend using dialog for anything more than simple notifications. When we use drag and drop from a dialog like component we use InteractionDialog.

Java3D disappearance act

It seems to me Java3D has a problem redrawing the scene sometimes when the Frame/JPanel/Canvas3D has been resized. I have a problem in my application using Java3D/JUNG3D where if the Frame/JPanel/Canvas3D's horizontal size is of certain size, the entire scene disappears. I was trying to simply the problem then found that a similar problem occurs in the following sample code: http://www.java3d.org/samples.html (The second to last example, "Text 3D Example") I will paste at the bottom for convenience.
Steps:
Install Java3D
Build this example using the 3 Java3D jars.
Run
Stretch the frame horizontally to 500 pixels or so then everything disappears. Shrink it back then it's there again. While things have disappeared, stretch vertically and things appear again.
It certainly seems to have something to do with the Frame/JPanel/Canvas3D aspect ratio and that of the content that it displays. My own problem is slightly different I'm guessing because I'm displaying scene of different aspect ratio and the underlying problem is the same. Can anyone tell me how I might be able to get around this bug/feature so that the scene never disappears when the window is resized?
Here are what I've tried so far with no success:
Catching the JPanel resize event then forcing the Canvas3D to redraw
Playing with double buffering settings
Many other things I can't recall right now - just came back from a vacation :)
Code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.*;
public class Titles {
public static void main(String[] args) {
Titles t = new Titles();
t.setUp();
}
public void setUp() {
JFrame jf = new JFrame("Welcome");
// kill the window on close
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent winEvent) {
System.exit(0);
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 1, 2, 2));
GraphicsConfiguration config = SimpleUniverse
.getPreferredConfiguration();
Canvas3D canvas3D = new Canvas3D(config);
canvas3D.setSize(360, 160);
SimpleUniverse universe = new SimpleUniverse(canvas3D);
BranchGroup group = new BranchGroup();
addObjects(group);
addLights(group);
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(group);
panel.add(canvas3D);
jf.getContentPane().add(panel, BorderLayout.CENTER);
jf.pack();
jf.setVisible(true);
}
public void addLights(BranchGroup group) {
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
1000.0);
Color3f light1Color = new Color3f(1.0f, 1.0f, 1.0f);
Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
DirectionalLight light1 = new DirectionalLight(light1Color,
light1Direction);
light1.setInfluencingBounds(bounds);
group.addChild(light1);
// Set up the ambient light
Color3f ambientColor = new Color3f(.1f, .1f, .1f);
AmbientLight ambientLightNode = new AmbientLight(ambientColor);
ambientLightNode.setInfluencingBounds(bounds);
group.addChild(ambientLightNode);
}
private void addObjects(BranchGroup group) {
Font3D f3d = new Font3D(new Font("TestFont", Font.PLAIN, 2),
new FontExtrusion());
Text3D text = new Text3D(f3d, new String("Java3D.org"), new Point3f(-3.5f,
-.5f, -4.5f));
text.setString("Java3D.org");
Color3f white = new Color3f(1.0f, 1.0f, 1.0f);
Color3f blue = new Color3f(.2f, 0.2f, 0.6f);
Appearance a = new Appearance();
Material m = new Material(blue, blue, blue, white, 80.0f);
m.setLightingEnable(true);
a.setMaterial(m);
Shape3D sh = new Shape3D();
sh.setGeometry(text);
sh.setAppearance(a);
TransformGroup tg = new TransformGroup();
Transform3D t3d = new Transform3D();
Transform3D tDown = new Transform3D();
Transform3D rot = new Transform3D();
Vector3f v3f = new Vector3f(-1.6f, -1.35f, -6.5f);
t3d.setTranslation(v3f);
rot.rotX(Math.PI / 5);
t3d.mul(rot);
v3f = new Vector3f(0, -1.4f, 0f);
tDown.setTranslation(v3f);
t3d.mul(tDown);
tg.setTransform(t3d);
tg.addChild(sh);
group.addChild(tg);
}
}
Try setting up a Buffer,Tutorial here. http://www.youtube.com/watch?v=vzfnUSLKUDs&list=ECA331A6709F40B79D
It's been 5 years but try this solution.
I tried it and it worked with lookAt() function.

Creating a closeable tab in Mono/GTK

I'm trying to create new GTK Notebook tabs that contain both a name (as a Label) and a close button (as a Button with an Image) with the following code:
Label headerLabel = new Label();
headerLabel.Text = "Header";
HBox headerBox = new HBox();
Button closeBtn = new Button();
Image closeImg = new Image(Stock.Close, IconSize.Menu);
closeBtn.Image = closeImg;
closeBtn.Relief = ReliefStyle.None;
headerBox.Add(headerLabel);
headerBox.Add(closeBtn);
headerBox.ShowAll();
MyNotebook.AppendPage(childWidget, headerBox);
This seems to work just fine; however, the button is about 1.5 - 2 times the size is needs to be, so there is a lot of extra space around the image inside the button. Having looked at remove inner border on gtk.Button I now see that the culprit is the "inner-border" style property of the GtkButton, but (being new to GTK) I can't seem to figure out how to override its value.
Is there some method of doing this that I'm missing? I don't have any reservations about not using a Button/Image combination, so any more obvious suggestions are welcome.
Note: I have seen the suggestion in the linked question to use an EventBox, but I was not able to add the Relief and mouseover effects to that Widget.
You are in luck. I just made the exact same thing yesterday, and can fortunately give you some code. The trick is to create a Custom Tab Widget.
public class MultiTab : Gtk.Box
{
public Gtk.Label Caption;
Gtk.Image img = new Gtk.Image(Platform.IMG + "tab_close.ico");
public Gtk.ToolButton Close;
public Gtk.Notebook _parent;
public MultiTab ( string name )
{
CreateUI(name);
}
public MultiTab(string name, Gtk.Notebook parent)
{
_parent = parent;
CreateUI(name);
CreateHandlers();
}
void CreateUI(string name)
{
Caption = new Gtk.Label(name);
Close = new Gtk.ToolButton(img,"");
PackStart( Caption );
PackStart( Close );
ShowAll();
Close.Hide();
}
void CreateHandlers()
{
Close.Clicked += delegate {
_parent.RemovePage(_parent.CurrentPage);
};
}
public bool Active;
}
Next all you have to do is use this widget(or a similar one created by you) in Gtk.Notebook like this:
MyNoteBook.AppendPage(new <YourPage>(), new MultiTab("<your caption>",this));
And You're done.
Here is a screenshot:
Add this:
RcStyle rcStyle = new RcStyle ();
rcStyle.Xthickness = 0;
rcStyle.Ythickness = 0;
closeBtn.ModifyStyle (rcStyle);
Add items to box using Gtk.Box.PackStart/PackEnd methods rather than generic Gtk.Container.Add method. PackStart/PackEnd will allow you control how child widgets will be allocated space:
headerBox.PackStart (headerLabel, true, true, 0);
headerBox.PackEnd (closeBtn, false, false, 0);

ITextSharp - text field in PdfPCell

I'm using iTextSharp to create a PDF, how can I add a textField into PdfPCell?
You wouldn't really add a 'text field' to a PdfPCell, you'd create a PdfPCell and add text (or other stuff) to that.
mikesdotnetting.com might have the clearest example and there's always the iTextSharp tutorial.
Give this a try. It works for me.
Document doc = new Document(PageSize.LETTER, 18f, 18f, 18f, 18f);
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
// Create your PDFPTable here....
TextField tf = new TextField(writer, new iTextSharp.text.Rectangle(67, 585, 140, 800), "cellTextBox");
PdfPCell tbCell = new PdfPCell();
iTextSharp.text.pdf.events.FieldPositioningEvents events = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, tf.GetTextField());
tbCell.CellEvent = events;
myTable.AddCell(tbCell);
// More code...
I adapted this code from this post.
Edit:
Here is a full working console application that puts a TextBox in a table cell. I tried to keep the code to a bare minimum.
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace iTextSharpTextBoxInTableCell
{
class Program
{
static void Main(string[] args)
{
// Create a PDF with a TextBox in a table cell
BaseFont bfHelvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);
Font helvetica12 = new Font(bfHelvetica, 12, Font.NORMAL, Color.BLACK);
Document doc = new Document(PageSize.LETTER, 18f, 18f, 18f, 18f);
FileStream fs = new FileStream("TextBoxInTableCell.pdf", FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
PdfPTable myTable = new PdfPTable(1);
myTable.TotalWidth = 568f;
myTable.LockedWidth = true;
myTable.HorizontalAlignment = 0;
TextField tf = new TextField(writer, new iTextSharp.text.Rectangle(67, 585, 140, 800), "cellTextBox");
PdfPCell tbCell = new PdfPCell(new Phrase(" ", helvetica12));
iTextSharp.text.pdf.events.FieldPositioningEvents events =
new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, tf.GetTextField());
tbCell.CellEvent = events;
myTable.AddCell(tbCell);
doc.Add(myTable);
doc.Close();
fs.Close();
Console.WriteLine("End Of Program Execution");
Console.ReadLine();
}
}
}
Bon chance
DaveB's answer works, but the problem is that you have to know the coordinates to place the textfield into, the (67, 585, 140, 800). The more normal method of doing this is to create the table cell and add a custom event to the cell. When the table generation calls the celllayout event it passes it the dimensions and coordinates of the cell which you can use to place and size the textfield.
First create this call, which is the custom event
public class CustomCellLayout : IPdfPCellEvent
{
private string fieldname;
public CustomCellLayout(string name)
{
fieldname = name;
}
public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases)
{
PdfWriter writer = canvases[0].PdfWriter;
// rectangle holds the dimensions and coordinates of the cell that was created
// which you can then use to place the textfield in the correct location
// and optionally fit the textfield to the size of the cell
float textboxheight = 12f;
// modify the rectangle so the textfield isn't the full height of the cell
// in case the cell ends up being tall due to the table layout
Rectangle rect = rectangle;
rect.Bottom = rect.Top - textboxheight;
TextField text = new TextField(writer, rect, fieldname);
// set and options, font etc here
PdfFormField field = text.GetTextField();
writer.AddAnnotation(field);
}
}
Then in your code where you create the table you'll use the event like this:
PdfPCell cell = new PdfPCell()
{
CellEvent = new CustomCellLayout(fieldname)
// set borders, or other cell options here
};
If you want to different kinds of textfields you can either make additional custom events, or you could add extra properties to the CustomCellLayout class like "fontsize" or "multiline" which you'd set with the class constructor, and then check for in the CellLayout code to adjust the textfield properties.