2014-10-01 57 views
0

我的JComboBox下拉列表中顯示酒店名稱列表中的問題。顯示ArrayList中的內容列表

我的ArrayList包含hotelNo,hotelName,city。

在我的GUI,我已經寫了這

Object[] hotelArr = { databaseconn.arrayListHere() }; 
    @SuppressWarnings({ "rawtypes", "unchecked" }) 
    // this just hide some unimportant warnings 
    JComboBox hotelList = new JComboBox(hotelArr); 
    hotelList.addActionListener(this); 
    frame.add(hotelList, BorderLayout.NORTH); 

我可以點擊下拉列表中,但只顯示「[]」。我認爲他們被稱爲括號。 我希望它顯示hotelName的列表,這也存儲在ArrayList hotelInfo中,我已經放入一個名爲arrayListHere的方法。

那我該怎麼做呢?在這個問題上花了很多時間。無法在任何地方找到答案或幫助。我也檢查了文檔,但沒有得到任何我可以使用的東西。

+0

,你可以做這行內容:System.out.println(databaseconn.arrayListHere());在開始的時候,告訴我們什麼是價值? – 2014-10-01 11:16:54

+0

是的。我剛剛做了,結果是「[]」。 (1,SAS Radisson,Copenhagen,2,Grosvenor Hotel,Copenhagen] [1,Sas Radisson,Copenhagen,2, Grosvenor Hotel,Copenhagen,3,Hilton,London] [1,Sas Radisson,Copenhagen,2,哥本哈根格羅夫納酒店3,倫敦希爾頓酒店,4,Ritz,Oslo] [1,Sas Radisson,Copenhagen,格羅夫納酒店,哥本哈根3,希爾頓酒店,倫敦4,里茲,奧斯陸,5,Best Western,null] 「 – 2014-10-01 11:20:26

+0

」[教程] /combobox.html)有關組合框的用法*如果您將其他對象放在組合框中,則默認渲染器會調用** toString **方法來提供一個字符串以顯示* – A4L 2014-10-01 11:20:38

回答

1

您的Object [] hotelArr被定義的方式不正確。此外,它不可能簡單地將一個列表投射到一個數組。相反,您必須將列表轉換爲數據結構,JComboBox才能處理。有幾種可能性:


1。(最好在我看來,這是因爲:

  • 保證類型安全,如果你正在處理其他類不是對象
  • arrayListHere()
  • 返回類型可以是接口Collection,這使得它更常見,比返回List

Collection<E> list = databaseconn.arrayListHere(); 
Vector<E> vector = new Vector(list); 
JComboBox box = new JComboBox(vector); 

如果你留在名單爲 arrayListHere()返回類型

2.

Object[] array = databaseconn.arrayListHere().toArray(); 
JComboBox box = new JComboBox(array); 
1

您的問題是,你得到一個空白[]和應將其作爲陣列(井 - 難以言傳,我將使用代碼這樣做)..

//you *certainly* get an array here 
Object[] list = databaseconn.arrayListHere(); 

//and as a result you get this code 
Object[] hotelArr = new Object[]{ list } ; 

當你則消息[] certainlty是ARRY是空的,至極使我的假設是databaseconn.arrayListHere()是一個空數組

你一個解決辦法是

Object[] hotelArr = (Object[]) databaseconn.arrayListHere(); 

但請認真檢查一下陣列,然後再將它放到前面!

1

你說你的ArrayList have 3鍵入pf數據,即hotelNo, hotelName, city

&現在您將其加載到Object[] hotelArr中,然後將其添加到JComboBox

那麼應用程序如何理解hotelNo, hotelName, city中的哪一個。

因此,讓另一個String[]只有hotelName

然後嘗試加載它在JComboBox,那麼它會工作。當您在對象數組中存在多重數據時,不能直接將對象添加到JCombobox。

如果你傳遞的是像hotemName這樣的單個數據集,那麼它就可以工作。看到這個:

List<String > ar = new ArrayList<>(); 
ar.add("hotel"); 
ar.add("hotel2"); 
ar.add("hotel3"); 

Object[] al = ar.toArray(); 

JComboBox j = new JComboBox(al); 
System.out.println(j.getItemCount()); 

請參閱this running example

+0

我已閱讀您的所有評論,我已盡力去做所有事情。我失敗了。我想我不明白如何去做。 有人能幫助我通過teamviewer什麼的? – 2014-10-01 12:30:43