【问题标题】:How to center a Label inside a RectangleFigure如何在矩形图形内居中标签
【发布时间】:2011-11-20 22:59:27
【问题描述】:

我是 draw2d 的新手,我正在尝试制作一些示例以了解如何使用它...我正在尝试编写一个显示白色背景标签的图形,一些填充,和封闭的灰色背景。为此,我写了以下内容:

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);
    }
}

我的类扩展了 Figure 而不是 RectangleFigure 因为我想稍后添加一个 ToolbarLayout,在 RectangleFigure+Label 下添加一些东西...现在我的问题:

  • 有没有办法让图形(标签)在其父图形 (RectangleFigure) 中居中,而无需像我一样计算位置?
  • 有什么方法可以为图形添加“填充”(产生类似于我在标签上设置的大小)或“边距”(根据其子项和边距自动计算的大小?
  • 一般来说,是否有更好的方法来实现我正在尝试做的事情?

我在 api 文档中找不到任何方法,而且总体上缺少一些文档...在此先感谢您。

【问题讨论】:

    标签: java eclipse-gef draw2d


    【解决方案1】:
    1. 您可以将矩形的布局设置为BorderLayout,然后将标签的约束设置为CENTER。这应该会自动处理居中。
    2. 您可以添加MarginBorder 来填充您的数字。
    3. 使用上面的两个答案可能会改进您的代码:-)

    【讨论】:

    • MarginBorder 帮我添加了填充。但是,BorderLayout 将标签的约束设置为 CENTER 不起作用,所以我仍然在我的问题中使用“手动”标签居中代码......非常感谢您的回答,几个月后(查看我的问题)!跨度>
    • 你是否将父级的布局设置为BorderLayout?应该工作。无论如何,如果您喜欢这个答案,为什么不将其标记为正确呢?
    猜你喜欢
    • 2018-04-19
    • 2019-07-13
    • 2019-03-14
    • 2013-05-04
    • 2023-01-01
    • 2022-01-05
    • 1970-01-01
    • 2022-11-02
    • 2022-01-08
    相关资源
    最近更新 更多