1

I'm a complete newbie with draw2d, i'm trying to make some examples in order to learn how to use it... I'm trying to write a Figure which shows a Label with white background, some padding, and an enclosing grey background. For that, i wrote the following:

public class MyFigure extends Figure {

    private Label label;
    private RectangleFigure rectangle;

    public MyFigure() {
        rectangle = new RectangleFigure();
        rectangle.setBackgroundColor(ColorConstants.gray);

        label = new Label("Test label");    
        label.setFont(new Font(null, "Arial", 12, SWT.BOLD));
        label.setTextAlignment(PositionConstants.CENTER);
        label.setBackgroundColor(ColorConstants.white);
        label.setForegroundColor(ColorConstants.black);
        label.setOpaque(true);

        rectangle.add(label);
        this.add(rectangle);
    }

    protected void paintFigure(Graphics graphics) {
        // Add padding to the label
        label.setSize(label.getTextBounds().resize(35, 10).getSize());
        // Set rectangle size, with some margin around the label
        Dimension d = label.getSize().expand(40, 10);
        rectangle.setSize(d);
        // Center the label inside the rectangle
        label.setLocation(rectangle.getLocation().translate(20, 5));

        // Finally, set this figure's bounds
        this.setBounds(rectangle.getBounds());

        super.paintFigure(graphics);
    }
}

My class extends Figure instead RectangleFigure because i want to add a ToolbarLayout later, to add things below the RectangleFigure+Label... Now my questions:

  • Is there any way to center a figure (Label) inside its parent (RectangleFigure) without calculating the position as i do?
  • Is there any way to add "padding" to figures (resulting in something like the size i set on the Label) or "margin" (size calculated automatically from its children and a margin?
  • Is there, in general, a better way to implement what i'm trying to do?

I can't find any method in the api docs, and there's some lack of documentation in general... Thank you in advance.

Baldrick
  • 23,882
  • 6
  • 74
  • 79
roirodriguez
  • 1,685
  • 2
  • 17
  • 31

1 Answers1

4
  1. You could set the layout of the rectangle to BorderLayout and then set the Label's constraint to CENTER. This should handle the centering automatically.
  2. You can add a MarginBorder to pad your figures.
  3. Using the two answers above will probably improve your code :-)
vainolo
  • 6,907
  • 4
  • 24
  • 47
  • MarginBorder helped me to add padding. BorderLayout setting the Label's constraint to CENTER didn't worked however, so i'm still using the "manual" Label centering code in my question... Thanks a lot for your answer, some months later (reviewing my questions)! – roirodriguez Jan 05 '12 at 09:10
  • Are you setting the parent's layout to BorderLayout? is should work. Anyway, if you like the answer, why not mark it as correct? – vainolo Jan 14 '12 at 19:50