我创建了一个Java SWT应用程序,我有一个包含标签的复合材料,标签的尺寸会不时变化。标签显示图像并具有监听器。 如何将标签置于复合材料内?
我创建了一个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));
我使用了这个功能:
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);
}
});
}
包含图像的标签贴在点(0,0)上,但我想把它放在复合材料的中心.....建议?
答案 0 :(得分:5)
请不要使用setBounds
或setSize
,除非必要,请改用Layout
。
请阅读:
以下是一些水平居中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();
}
}
}
看起来像这样: