2011-01-27 12 views
8

データベーススキーマ= JComboboxにJTableカラムとして表示され、名前を選択します。しかし、IDフィールドを別のテーブルに(外部キーとして)挿入する必要があります。JComboboxの文字列アイテム(可視)と整数キー(固有)

通常、ドロップダウンで項目を選択すると、選択した項目がコンボボックスの表示された領域に移動します。

コンボボックスでアイテム(文字列)を選択すると、対応する整数キー(ソートされたマップに保持できる)がコンボボックスのプレースホルダ領域に表示されるようにして、値JTable.getValueAt(行、列)のうち、文字列項目値ではなく、整数キーが取得されます。 どうすればいいですか?

答えて

-2

それを行うには自動的な方法が存在しないため:( 私は私の値とキーを維持するために地図を使用しています

private TreeMap <Integer, String> categoryMap = new TreeMap<Integer, String>(); 
private JComboBox comboCategory = new JComboBox(); 

は、すべてのカテゴリ(キー、値)を取得し、地図やコンボ

private void addComboColumnData() { 
     try { 
      Class.forName("org.sqlite.JDBC"); 
      Connection conn = DriverManager.getConnection(conURL); 
      Statement stat = conn.createStatement(); 
      ResultSet rs = stat.executeQuery("SELECT id, name FROM categories");    
      comboCategory.removeAllItems(); 
      comboCategory.addItem(""); // blank value. 
      categoryMap.clear(); 
      while(rs.next()){ 
       String name = rs.getString("name"); 
       comboCategory.addItem(name); 
       categoryMap.put(rs.getInt("id"), name); 
      }   
      rs.close(); 
      conn.close(); 
     } catch (Exception e){ 
      JOptionPane.showMessageDialog(this, e.toString()); 
      e.printStackTrace(); 
     } 
    } 

FOを取り込みますurth私のJTableの列のは

// set the fourth column as combo 
      TableColumn categoryColumn = tableData.getColumnModel().getColumn(4); 
      categoryColumn.setCellEditor(new DefaultCellEditor(comboCategory)); 

コンボボックスの値を編集し、それがテキストを表示するが、データベーステーブルの値を更新するために、私は、整数キーを取得する必要があり、コンボボックスにする必要があります。データベースの更新のために

// show Category name in text in the category field. 
        if(columnNames[i].equalsIgnoreCase("category")){ 
         Object obj = rs.getObject(i+1); 
         if(obj != null && (obj instanceof Integer)) 
          row[i] = (String) categoryMap.get((Integer) obj); 
        } 

、ここ

Object value = tableData.getModel().getValueAt(rowIndex, 4); 
     int categoryID = 0; 

     if(value!= null){ 
      if (value instanceof String && !((String)value).isEmpty()) { 
       categoryID = getKeyForValue((String)value); 
      } else if(value instanceof Number) { 
       categoryID = (Integer) value; 
      } 
     } 

とgetKeyForValue、

private int getKeyForValue(String value) { 
    for (Entry<Integer, String> entry : categoryMap.entrySet()) { 
     if (entry.getValue().equals(value)) { 
      return entry.getKey(); 
     } 
    } 
    return 0; 
} 
13

表示する文字列値とキーの整数値の両方を含むTableModelにオブジェクトを格納する必要があります。次に、両方の情報を含むオブジェクトにアクセスできるtable.getValueAt(...)にアクセスします。ここで

は、スタンドアロンのコンボボックスの例です。

import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 
import javax.swing.plaf.basic.*; 

public class ComboBoxItem extends JFrame implements ActionListener 
{ 
    public ComboBoxItem() 
    { 
     Vector model = new Vector(); 
     model.addElement(new Item(1, "car")); 
     model.addElement(new Item(2, "plane")); 
     model.addElement(new Item(3, "train")); 
     model.addElement(new Item(4, "boat")); 
     model.addElement(new Item(5, "boat aadf asfsdf a asd asd")); 

     JComboBox comboBox; 

     // Easiest approach is to just override toString() method 
     // of the Item class 

     comboBox = new JComboBox(model); 
     comboBox.addActionListener(this); 
     getContentPane().add(comboBox, BorderLayout.NORTH); 

     // Most flexible approach is to create a custom render 
     // to diplay the Item data 

     comboBox = new JComboBox(model); 
     comboBox.setRenderer(new ItemRenderer()); 
     comboBox.addActionListener(this); 
     getContentPane().add(comboBox, BorderLayout.SOUTH); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
     JComboBox comboBox = (JComboBox)e.getSource(); 
     Item item = (Item)comboBox.getSelectedItem(); 
     System.out.println(item.getId() + " : " + item.getDescription()); 
    } 

    class ItemRenderer extends BasicComboBoxRenderer 
    { 
     public Component getListCellRendererComponent(
      JList list, Object value, int index, 
      boolean isSelected, boolean cellHasFocus) 
     { 
      super.getListCellRendererComponent(list, value, index, 
       isSelected, cellHasFocus); 

      if (value != null) 
      { 
       Item item = (Item)value; 
       setText(item.getDescription().toUpperCase()); 
      } 

      if (index == -1) 
      { 
       Item item = (Item)value; 
       setText("" + item.getId()); 
      } 


      return this; 
     } 
    } 

    class Item 
    { 
     private int id; 
     private String description; 

     public Item(int id, String description) 
     { 
      this.id = id; 
      this.description = description; 
     } 

     public int getId() 
     { 
      return id; 
     } 

     public String getDescription() 
     { 
      return description; 
     } 

     public String toString() 
     { 
      return description; 
     } 
    } 

    public static void main(String[] args) 
    { 
     JFrame frame = new ComboBoxItem(); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

} 
+2

時には私は嫌いjava..to単純なタスクには非常に多くのコードがあります – aswzen

0

である私は素晴らしいとスマートなソリューションがあります。

ResultSet resultSet = userBL.loadRoles(); 
      try { 
       Vector<Roles> vector = new Vector<>(); 
       while (resultSet.next()) { 
        vector.addElement(new Roles(resultSet.getInt(1), resultSet.getString(2)));             
       } 
       rolComboBox.setModel(new DefaultComboBoxModel(vector));    
      } catch (SQLException e) { 
       System.out.println("SQLException LoadRoles Combo:"+e); 
      } 

を私がするためのモデルを設定rolComboBoxとcを含むベクトルustom Objectの場合、resultSetオブジェクトには、データベースからのすべてのデータが含まれます。 その後、comboBoxからIDを取得したい場合は、getSelectedItemという方法で取得してください。

System.out.println("Rol Selected: "+ ((Roles)rolComboBox.getSelectedItem()).getId()); 
関連する問題