Java的SWT - 添加按钮外壳

问题描述 投票:2回答:1

我试图创建一个使用下面的代码按钮的简单窗口:

public static void main(String[] args) 
{       
    Display display=new Display();
    Shell shell=new Shell();

    shell.open();
    shell.setText("Hi there!");
    shell.setSize(500,500);

    Button pushButton = new Button(shell, SWT.PUSH);
    pushButton.setText("Im a Push Button");
    //pushButton.pack();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

    shell.dispose();
}

当注释掉“pushButton.pack()”行,该按钮将不会出现在窗口上。是不是真的有必要呼吁每一个按钮,我想添加的包()方法? 如果我有10个按钮?

for (int i=0; i<10; i++) {
    new Button(shell, SWT.RADIO).setText("option "+(i+1));
}

它如何工作呢?

另外,是否有适合初学者的好SWT的教程在网上? 你能推荐一本书,可以指导我通过SWT?

java swt
1个回答
2
投票

你的程序应该是这样的:

public static void main(String[] args) 
{       
    Display display=new Display();
    Shell shell=new Shell();

    // Set a layout
    shell.setLayout(new FillLayout());
    shell.setText("Hi there!");

    Button pushButton = new Button(shell, SWT.PUSH);
    pushButton.setText("Im a Push Button");

    // Move the shell stuff to the end
    shell.pack();
    shell.open();
    shell.setSize(500,500);

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

这样一来,你只能在pack()致电Shell一次。


这些是绝对必备读取SWT初学者:

© www.soinside.com 2019 - 2024. All rights reserved.