繁体   English   中英

JComboBox的问题

[英]Problems with JComboBox

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);

    } }

正如您从上面的代码中看到的那样。 我有4个项目的JComboBox。 如果没有相同的项目一切正常。

但在我的例子中(“AAS1”,“AAS2”,“AAS1”,“AAS3”),第一和第三项是相同的,在这种情况下我遇到了问题。 当我选择任何项目时,我想在JTextField中获取它的索引,但是当我选择第三项时,我得到第一项的索引。 有什么想法吗?

那是因为JComboBox使用equals来检查项目是否相等。 在您的情况下,这两个String是相等的,因此它返回匹配的第一个索引。 如果你真的需要这样做,你可能需要像这样定义自己的项类:

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);

创建一个这样的类:

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")
});

您必须分别如何计算String的项目和有效表示的equals。 我认为这可以通过为您的目的创建一个特定的类来完成,并使用它而不是String

由于这可能是家庭作业,我不会给出确切的结果,只需考虑JComboBox如何在内部选择指定的索引。

尝试使用combo.getSelectedItem()代替。 由于字符串数组中有两个不同的字符串,因此您应该能够进行参考比较并区分两者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM