[英]How center label inside composite SWT Java
I have created a Java SWT application and I have a composite containing a label with dimensions that change from time to time. 我已经创建了一个Java SWT应用程序,并且有一个包含标签的复合文件,其标签会不时变化。 The label displays an Image and have listener.
标签显示图像并具有侦听器。 How can I center the label inside the composite?
如何将标签居中放置在复合材料中?
I have created a shell with: 我用以下方法创建了一个shell:
Composite conteinerBox = new Composite(shell, SWT.NONE);
conteinerBox.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
conteinerBox.setBounds(342, 10, 410, 384);
Label imageContainer = new Label(conteinerBox,SWT.NONE);
imageContainer.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
I used this function: 我使用了这个功能:
private void openImage() {
if(isAnImage(file.getPath())){
System.out.println("FILE OPEN : " + file.getPath());
Image image = getImage(file.getPath());
//attach image
imageContainer.setSize(image.getBounds().width,image.getBounds().height);
imageContainer.setImage(image);
//set image mouse listener
imageContainer.addMouseMoveListener(new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent event) {
x_mouse_cordinate.setText("" + event.x);
y_mouse_cordinate.setText("" + event.y);
}
});
}
The label containing the image is attached on point(0,0) but I want to center it inside the composite.....suggestions? 包含图像的标签粘贴在point(0,0)上,但我想将其放置在复合材料内部的中心.....建议?
Please DO NOT use setBounds
or setSize
unless necessary, use Layout
s instead. 除非必要,否则请勿使用
setBounds
或setSize
,而应使用Layout
。
Please read this: 请阅读这个:
Understanding Layouts in SWT 了解SWT中的布局
Here is some example code that centers the Label
horizontally: 以下是一些将
Label
水平居中的示例代码:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new GridLayout(1, false));
final Label centered = new Label(shell, SWT.NONE);
centered.setText("Small text");
centered.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, true));
Button changeText = new Button(shell, SWT.PUSH);
changeText.setText("Change text");
changeText.addListener(SWT.Selection, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
centered.setText("Loooooooooooooooooooong text");
centered.getParent().layout();
}
});
shell.pack();
shell.setSize(600, 200);
shell.open();
while (!shell.isDisposed())
{
while (!display.readAndDispatch())
{
display.sleep();
}
}
}
Looks like this: 看起来像这样:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.