gpt4 book ai didi

java - 如何在矩形图形中居中放置标签

转载 作者:行者123 更新时间:2023-11-29 06:09:21 25 4
gpt4 key购买 nike

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

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

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

我在 api 文档中找不到任何方法,而且通常缺少一些文档...提前谢谢您。

最佳答案

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

关于java - 如何在矩形图形中居中放置标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7483443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com