2012-07-19 50 views
2

未設置邊界,我的標籤未按預期在下面的代碼中顯示。 我在shell中創建一個Composite,因爲我只想讓背景圖像出現在這個組合中。未在合成內顯示Eclipse SWT標籤

在這種情況下,該綁定應該是什麼?我可以根據標籤的文字獲得最佳範圍嗎?

Display display = PlatformUI.createDisplay(); 
Shell shell = new Shell(display); 
shell.setText("Header); 

Composite main = new Composite(shell, SWT.NONE); 
main.setBounds(10, 5, 775, 505); 
InputStream is = getClass().getResourceAsStream("/resources/bg.png"); 
Image bg = new Image(display, is); 
main.setBackgroundImage(bg);   
main.setBackgroundMode(SWT.INHERIT_DEFAULT); 

Label label = new Label(main, SWT.NONE);    
//label.setBounds(0, 0, 400,100);   // not showing if commented away 
label.setText("Label 1"); 
+0

你嘗試'main.pack()'或'shell.pack()'? – Baz 2012-07-19 08:58:22

+2

此外,你似乎並沒有使用佈局。有關概覽,請參閱http://www.eclipse.org/articles/article.php?file=Article-Understanding-Layouts/index.html。 – Baz 2012-07-19 09:08:16

+0

我以爲我在默認的GridLayout的地方閱讀它。糾正我,如果我錯了。 – humansg 2012-07-19 10:08:15

回答

3

這對我的作品在Linux(Eclipse的3.6.2,Java的1.6.0.26):

public class StackOverflow 
{ 
    public static void main(String[] args) 
    { 
     Display display = Display.getDefault(); 
     Shell shell = new Shell(display); 
     shell.setText("Header"); 

     Composite main = new Composite(shell, SWT.NONE); 
     main.setLayout(new GridLayout(1, false)); 
     Image bg = new Image(display, "resources/bg.png"); 
     main.setBackgroundImage(bg); 
     main.setBackgroundMode(SWT.INHERIT_DEFAULT); 

     Label label = new Label(main, SWT.NONE);  
     label.setLayoutData(new GridData(GridData.FILL_BOTH)); 
     label.setText("Label 1"); 

     main.pack(); 
     main.setBounds(10, 5, 775, 505); 
     shell.pack(); 
     shell.open(); 
     while (!shell.isDisposed()) 
     { 
      if (!display.readAndDispatch()) 
       display.sleep(); 
     } 
    } 
} 
+0

嘿巴茲,非常感謝您的幫助。我輸入你的代碼,它工作。它意識到main.setBounds需要在將所有組件添加到Composite之後調用。我最初的代碼是它在聲明後被直接設置,這導致了這個問題。我還了解到,無論您在setBounds中設置了多少寬度/高度,調用pack()後都會調整爲「最優」大小! – humansg 2012-07-20 01:43:39