2014-10-08 34 views
0

我是自學的Java GUI,並且試圖實現一個較老的基於文本的程序,我使用某個實際菜單進行了某些操作。在Eclipse上使用WindowBuilder格式化和互聯網資源來幫助,但我遇到了一些障礙。使用字符串向量填充SWT表

我有一個一維矢量,可以容納任意數量的字符串。我想將它顯示在表格中,但我不確定是否正確。我所有的後端工作都能正常工作,我只是非常努力地使用GUI。非常感謝您願意提供的任何提示/更正/資源!我一直在困擾幾個小時,我擔心我碰到了一堵牆。說實話,我在WindowBuilder中也很難測試GUI,但那是另一回事。在我的GUI類相關的代碼如下:

Vector<String> demo = new Vector<String>(); 
    //nonsense elements just for the sake of debugging 
    demo.addElement("Line1"); 
    demo.addElement("Line2"); 
    demo.addElement("Line3"); 
    demo.addElement("Line4"); 
    demo.addElement("Line5"); 
    demo.addElement("Line6"); 


    table = new Table(this, SWT.BORDER | SWT.FULL_SELECTION); 
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); 
    table.setHeaderVisible(true); 
    table.setLinesVisible(true); 

    TableItem item; 
    for(int i = 0; i < demo.size(); i++) 
    { 
     // Create a new TableItem for each line in the vector (each row) 
     item = new TableItem(table, SWT.NONE); 
     for (int j = 1; j <= demo.size(); j++) { 
      // Populate the item 
      item.setText(j - 1, demo.get(j)); 
     } 
    } 
+2

有點風馬牛不相及,但:請不要使用'VECTOR'(http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete - 或者不推薦使用) – Baz 2014-10-08 06:42:32

+0

那麼,究竟是不是工作? – Baz 2014-10-08 09:42:39

+0

另外,感謝關​​於矢量的頭像。我一定會記住,對於未來的項目! – mKane848 2014-10-08 17:20:29

回答

2

問題是這樣的一行:

item.setText(j - 1, demo.get(j)); 

你只有一列(因爲你沒有創建任何自己,表假設有隻有一列),但使用TableItem#setText(int, String)會設置i列中的文本(對於其中一個項目,其等於0)。

那麼,如果你剛剛得到了一個列,使用此:

item.setText(demo.get(j)); 

item.setText(0, demo.get(j)); 

如果你有更多的colums,添加條目之前創建它們(new TableColumn(table, SWT.NONE))然後使用添加項目:

for(int i = 0; i < items.size(); i++) 
{ 
    TableItem item = new TableItem(table, SWT.NONE); 

    for(int j = 0; j < table.getColumnCount(); j++) 
    { 
     item.setText(j, "something here"); 
    } 
} 

然後事後你必須pack()的列:

for(TableColumn col : table.getColumns()) 
{ 
    col.pack(); 
} 
+0

好的,真棒。我想我想添加另一列(只需要在每行旁邊有一個數字),這樣可以大大增加額外的位數!答案沿着關於載體的信息是偉大的,謝謝你的時間 – mKane848 2014-10-08 19:53:53

+0

@ mKane848偉大的,那麼請考慮接受我的答案。 – Baz 2014-10-08 19:55:33

+1

對不起!以爲我在關閉該頁面之前打了它 – mKane848 2014-10-08 22:31:02