swt同时创建label和button控件,并有良好布局
时间: 2023-11-22 18:56:26 浏览: 33
可以使用 SWT 的布局管理器来实现良好的布局。以下是一个例子,其中创建了一个 Label 和一个 Button 控件,并使用了 GridLayout 布局管理器:
```java
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class LabelButtonExample {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(2, false)); // 2列,不等宽
// 创建 Label 控件
Label label = new Label(shell, SWT.NONE);
label.setText("Hello, SWT!");
// 创建 Button 控件
Button button = new Button(shell, SWT.PUSH);
button.setText("Click me!");
// 设置布局参数
label.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
button.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
// 打开窗口
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
```
在这个例子中,我们创建了一个 Shell 并设置了 GridLayout 布局管理器。然后,我们创建了一个 Label 和一个 Button 控件,并设置它们的文本。接下来,我们为它们设置了布局参数,以使它们居中显示。最后,我们打开了窗口并进入了事件循环。