如何在另一个标签上放置标签?

时间:2014-06-11 14:09:00

标签: java swt

是否可以在另一个标签上放置标签?我有一个具有特定背景颜色的标签,我想在其上面放置一个具有不同背景颜色的第二个标签。

这可能吗?我希望smallBar能够在bigBar之上。 我正在改变各种活动中smallBar的大小,所以我希望它能不断上升。

public class GuessBarComposite extends Composite{
  public GuessBarComposite(Composite shell, int style){
    super(shell,style);
    bigBar = new Label(this,SWT.NONE);
    smallBar = new Label(this, SWT.NONE);

    Color outOfRangeColor= new Color(Display.getDefault(), 139,0,0);
    Color inRangeColor= new Color(Display.getDefault(), 255,140,0);

    bigBar.setBounds(labelOffset,20,barWidth, barHeight);
    bigBar.setBackground(outOfRangeColor);

    smallBar.setBounds(labelOffset,20,barWidth-20, barHeight);
    smallBar.setBackground(inRangeColor);
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用StackLayoutLabel置于彼此之上,然后您可以通过设置StackLayout#topControl来切换它们。这是一个例子:

public static void main(String args[])
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(1, false));

    final StackLayout stackLayout = new StackLayout();

    final Composite stack = new Composite(shell, SWT.NONE);
    stack.setLayout(stackLayout);

    Label bottom = new Label(stack, SWT.NONE);
    bottom.setText("Bottom");

    Label top = new Label(stack, SWT.NONE);
    top.setText("Top");

    stackLayout.topControl = top;

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Switch");
    button.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            stackLayout.topControl = stackLayout.topControl.equals(top) ? bottom : top;
            stack.layout(true, true);
        }
    });

    shell.pack();
    shell.open();

    while (!shell.isDisposed())
    {
        if (!shell.getDisplay().readAndDispatch())
            shell.getDisplay().sleep();
    }
}

如果您只是希望它们一个接一个地出现(在y位置的顶部),那么使用GridLayout

public static void main(String args[])
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(1, false));

    Label bottom = new Label(shell, SWT.NONE);
    bottom.setText("Bottom");

    Label top = new Label(shell, SWT.NONE);
    top.setText("Top");

    shell.pack();
    shell.open();

    while (!shell.isDisposed())
    {
        if (!shell.getDisplay().readAndDispatch())
            shell.getDisplay().sleep();
    }
}