【问题标题】:Set Selected Item JComboBox from String从字符串中设置选定项 JComboBox
【发布时间】:2017-05-23 03:03:21
【问题描述】:

我有一个JComboBox,它的值由两部分 int-String 构建而成,如下所示:

01-one
02-two
03-three

所以现在我只有String 部分,并想setSelectedItem 这个部分的项目,但我认为这是不可能的,因为值不匹配或不一样

myComboBox.setSelectedItem("?" + myString);

所以我想做的是:

myComboBox.setSelectedItem("like myString");

有人有想法设置选择与组合框中的值类似的项目,否则这是不可能的?

【问题讨论】:

  • 是的,有可能——您必须创建一个方法来检查一个字符串是否与另一个字符串足够相似,并可能返回一个数值或真值,并使用它来确定将所选项目设置为哪个索引。
  • 嗯,我真的不认为这个解决方案,谢谢@HovercraftFullOfEels 这可以帮助我:)

标签: java swing jcombobox


【解决方案1】:

您可以尝试使用.contains 方法,查看组合框中的第一项是否包含该特定单词并重复它直到找到特定索引。

例如:

if (jComboBox1.getItemAt(0).toString ().contains ("two")) 
{ 
    jComboBox1.setSelectedIndex(0);
}

然后重复该步骤或尝试使用 for 循环,如果您的组合框包含许多项目,那就太好了。

【讨论】:

    【解决方案2】:

    如果您希望能够通过字符串精确选择,这就是您在描述中指出的内容,我将创建一个类来表示您的特定项目,将 int 和 string 作为单独的字段在其中维护,并覆盖 @ 987654321@ 返回您想要的表示。然后,您可以使用一种方法仅根据字符串搜索您的项目。对于数量相对较少的项目,这是高效且简单的。如果您有大量项目,我建议将它们作为值存储在 HashMap 中,使用字符串作为键。

    import java.awt.BorderLayout;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    
    class Item {
      int intValue;
      String strValue;
    
      public Item(int intValue, String strValue) {
        this.intValue = intValue;
        this.strValue = strValue;
      }
    
      public String toString() {
        return intValue + " - " + strValue;
      }
    }
    
    public class TestCombo {
      private static JComboBox<Item> cb;
      public static void main(String[]args) {
        JFrame f = new JFrame();
        f.setSize(640,400);
        cb = new JComboBox<>();
        cb.addItem(new Item(1, "one"));
        cb.addItem(new Item(2, "two"));
        cb.addItem(new Item(3, "three"));
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(cb, BorderLayout.NORTH);
        f.setVisible(true);
    
        selectItemByString("three");
      }
    
      private static void selectItemByString(String s) {
        for (int i=0; i<cb.getItemCount(); i++) {
          if (cb.getItemAt(i).strValue.equals(s)) {
            cb.setSelectedIndex(i);
            break;
          }
        }
        return;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多