使用 GridData 对齐 + 填充标签中的 SWT 问题

SWT Issue in Aligning + Filling a Label with GridData

所以,我尝试制作一个小游戏,您必须执行由标签显示的操作。

我的问题是我无法将列中心的标签对齐 AND 用标签填充整个 space 列,这样我就可以使用背景 cColor。

例如:

Shell shell = new Shell(display);
        
GridLayout layout = new GridLayout();
Font font = new Font(display, "Arial", 30, SWT.NONE);

layout.numColumns = 2;
layout.marginHeight = 0;
layout.marginWidth = 0;

shell.setText("ReactionGame 2.0");
shell.setMaximized(true);
shell.setLayout(layout);
shell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));

GridData data1 = new GridData(SWT.CENTER, SWT.CENTER, true, true);
        
data1.verticalAlignment = GridData.FILL;
data1.horizontalAlignment = GridData.FILL;
        
Label lifelabel = new Label(shell, SWT.NONE);

lifes(lifelabel);
lifelabel.setForeground(display.getSystemColor(SWT.COLOR_RED));
lifelabel.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
lifelabel.setFont(font);

lifelabel.setLayoutData(data1);
        
Label scorelabel = new Label(shell, SWT.NONE);
        
scorecount(scorelabel);
scorelabel.setForeground(display.getSystemColor(SWT.COLOR_RED));
scorelabel.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
scorelabel.setFont(font);
        
scorelabel.setLayoutData(data1);
        
        Label gamelabel = new Label(shell, SWT.NONE);

gamelabel.setText("");
gamelabel.setForeground(display.getSystemColor(SWT.COLOR_GREEN));
gamelabel.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
gamelabel.setFont(font);

        gamelabel.setLayoutData(data1);

This code gives me a design of this:

我现在的问题是如何将标签的文本居中对齐?

您正在为多个控件重复使用相同的 GridData (data1) - 这是不允许的。 GridData实例用于保存各个控件的布局信息,您必须为每个控件使用一个新实例。

所以使用:

lifelabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

scorelabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

gamelabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

要制作第三个区域,您需要使用额外的 Composite,标签居中并设置背景颜色:

Composite gameComp = new Composite(shell, SWT.NONE);

gameComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

gameComp.setBackground(display.getSystemColor(SWT.COLOR_RED));

GridLayout gameLayout = new GridLayout();
gameLayout.marginHeight = 0;
gameLayout.marginWidth = 0;
gameComp.setLayout(gameLayout);

Label gamelabel = new Label(gameComp, SWT.NONE);

gamelabel.setText("game");
gamelabel.setForeground(display.getSystemColor(SWT.COLOR_GREEN));
gamelabel.setBackground(display.getSystemColor(SWT.COLOR_RED));
gamelabel.setFont(font);

gamelabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));