這是我的第一個問題,但我很困難。也許這只是我過去幾天的極度疲勞,但我現在幾個小時查了谷歌,找不到任何接近良好的答案。Java SWT:小部件(按鈕,標籤)使用正確
我知道SWT是像我能想到的所有GUI一樣的事件驅動,當創建小部件時,我應該記住他們需要能夠達到他們應該修改/交互的部件。但我需要知道的是,如果我的想法是對的,如果不是,我應該改進什麼。
比方說,我從eclipse + windowbuilder + swt/jface java項目開始。然後,添加按鈕,clabel +點擊按鈕(SelectionListener中)監聽器,所以生成的代碼看起來多少有點像(僅適用於主法,上面有唯一的主類和進口)
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell();
shell.setSize(450, 300);
shell.setText("SWT Application");
Button btnNewButton = new Button(shell, SWT.NONE);
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
btnNewButton.setBounds(51, 31, 75, 25);
btnNewButton.setText("New Button");
CLabel lblOneTwo = new CLabel(shell, SWT.NONE);
lblOneTwo.setBounds(180, 119, 61, 21);
lblOneTwo.setText("one two");
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
據我所知,它的可能明顯對大多數的你我不能只是去,並加入到
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
代碼像lblOneTwo.setText("three")
,從我知道,有時用我只是聲明所有的東西事前,作爲static widget widgetName
然後我可以從基本訪問它們無處不在,所以代碼如
static Button btnNewButton;
static CLabel lblOneTwo;
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell();
shell.setSize(450, 300);
shell.setText("SWT Application");
btnNewButton = new Button(shell, SWT.NONE);
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
lblOneTwo.setText("three");
}
});
(...)
工作得很好。但我猜想,這不是最好的做法和做法,不是嗎?所以,請幫助我,指出我正確的方向,以便我可以停止編碼犯罪。提前致謝!與文章/教程鏈接的間接回答將非常棒,但我喜歡人們放在這裏的例子,因爲他們展示事物的方式很明確。
前兩個選項被證明是共享非常有用和感謝。我已經做了我昨天想要的東西,但是在你的帖子之後,我重寫了一下,使它更清晰:) – ilmash
@ilmash很高興爲你效勞! – Baz