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問題
有趣的問題,但我無法想象這在教室外發生。 – user1329572 2012-04-16 17:47:22
我必須在項目中使用這個東西,你能幫助我嗎? – Karen 2012-04-16 17:50:30
爲什麼索引0和2是相同的?用戶應該如何區分它們? – 2012-04-16 18:08:05