开发者

How to center a Label inside a RectangleFigure

开发者 https://www.devze.com 2023-04-06 06:53 出处:网络
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 e

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.p开发者_如何转开发aintFigure(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.


  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 :-)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号