布局问题:自动增长标签(SWT)

2023-12-12

我正在使用 GridLayout 尝试使标签自动增长而不隐藏其任何内容。这是一个要测试的简单代码:每次按下按钮时,标签文本都会变大,但只有在水平调整窗口大小后,我才能获得正确的布局。 有没有什么方法可以解决这个问题而无需调整窗口大小? 我想我已经尝试了所有属性,但仍然无法正常工作,这让我发疯!

这就是我得到的

wrong layout

事情应该是这样的

right layout

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
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.List;
import org.eclipse.swt.widgets.Shell;

public class UItest {

    protected Shell shell;
    private Label   label;

    public static void main(String[] args) {
        try {
            UItest window = new UItest();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void open() {
        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }

    protected void createContents() {
        shell = new Shell();
        shell.setSize(450, 300);
        shell.setText("SWT Application");
        shell.setLayout(new GridLayout(1, false));

        Button button = new Button(shell, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent arg0) {
                label.setText(label.getText() + " " + label.getText());
            }
        });
        button.setText("New Button");

        label = new Label(shell, SWT.WRAP);
        label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        label.setText("New Label");

        List list = new List(shell, SWT.BORDER);
        list.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    }

    protected Label getLabel() {
        return label;
    }
}

谢谢你的时间。


通过这些更改解决了:

Button button = new Button(shell, SWT.NONE);
button.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent arg0) {
        label.setText(label.getText() + " " + label.getText());
        shell.layout(); // ADDED THIS
    }
});
button.setText("New Button");

label = new Label(shell, SWT.WRAP);
// SET HORIZONTAL GRAB ON LABEL (FIRST TRUE IN GridData CONSTRUCTOR)
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
label.setText("New Label");

我认为,问题在于文本更改时布局不会失效 - 尝试强制重新布局(通过调用getShell().layout(true, true)).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

布局问题:自动增长标签(SWT) 的相关文章

随机推荐