2012-04-16 77 views
4
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ItemEvent; 
import java.awt.event.ItemListener; 

public class Test1{ 
    JComboBox combo; 
    JTextField txt; 

    public static void main(String[] args) { 
     Test1 b = new Test1(); 
    } 

    public Test1(){ 
     String degrees[] = {"AAS1","AAS2","AAS1","AAS3"}; 
     JFrame frame = new JFrame("Creating a JComboBox Component"); 
     JPanel panel = new JPanel(); 

     combo = new JComboBox(degrees); 
     combo.setEditable(true); 
     combo.setBackground(Color.gray); 
     combo.setForeground(Color.red); 

     txt = new JTextField(10); 
     txt.setText("1"); 

     panel.add(combo); 
     panel.add(txt); 
     frame.add(panel); 

     combo.addItemListener(new ItemListener(){ 
      public void itemStateChanged(ItemEvent ie){ 
       txt.setText(String.valueOf(combo.getSelectedIndex()+1)); 
      } 
     }); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(400,400); 
     frame.setVisible(true); 

    } } 

正如您從上面的代碼中看到的那樣。我有JComboBox 4項。如果沒有相同的項目,則一切正常。在我的例子中(「AAS1」,「AAS2」,「AAS1」,「AAS3」)第一項和第三項相同,在這種情況下我有問題。 當我選擇任何項目時,我想在JTextField中獲取它的索引,但是當我選擇第三個項目時,我獲取第一個項目的索引。 有什麼想法?JComboBox問題

+0

有趣的問題,但我無法想象這在教室外發生。 – user1329572 2012-04-16 17:47:22

+0

我必須在項目中使用這個東西,你能幫助我嗎? – Karen 2012-04-16 17:50:30

+2

爲什麼索引0和2是相同的?用戶應該如何區分它們? – 2012-04-16 18:08:05

回答

4

這是因爲JComboBox可使用equals進行檢查的項目平等。在你的情況下,這兩個字符串是相等的,所以它返回匹配的第一個索引。如果你真的需要做到這一點,你可能需要像這樣定義自己的物品類別:

private static class MyItem { 
    private String value; 

    public MyItem(String value) { 
     this.value = value; 
    } 

    public String getValue() { 
     return value; 
    } 

    @Override 
    public String toString() { 
     return value; //this is what display in the JComboBox 
    } 
} 

,然後添加的項目是這樣的:

MyItem degrees[] = {new MyItem("AAS1"),new MyItem("AAS2"),new MyItem("AAS1"),new MyItem("AAS3")}; 
JComboBox combo = new JComboBox(degrees); 
0

您必須分隔如何在String的項目上計算等於和有效表示。我認爲這可以通過爲你的目的創建一個特定的類來完成,而不是使用String

因爲這可能是功課,我不會給出確切的結果,只要想想JComboBox如何在內部選擇指定的索引。

+0

這不是家庭作業我必須在實際應用中使用這個東西。這只是一個小例子,可以顯示我想要的。 – Karen 2012-04-16 17:53:40

0

嘗試使用combo.getSelectedItem()代替。由於它在字符串數組中有兩個不同的字符串,因此您應該能夠進行參考比較並分辨兩者之間的差異。

+0

我需要選擇的物品索引 – Karen 2012-04-16 17:57:53

+0

無論如何都無法正常工作。 :/ – 2012-04-16 17:59:31

+0

然後它應該被刪除,如果它不起作用 – hd1 2016-04-03 22:35:12

2

創建一個這樣的類:

class ComboItem{ 

    private String name; 

    public ComboItem(String name){ 
     this.name = name; 
    } 

    public String toString() { 
     return name; 
    } 
} 

,並創建您的組合框:

comboBox = new JComboBox(new ComboItem[]{ 
    new ComboItem("AAS1"), 
    new ComboItem("AAS2"), 
    new ComboItem("AAS1"), 
    new ComboItem("AAS3") 
});