2013-03-03 68 views
0

我是Java编程的初学者。我想在Jtable中使用JComboBox作为单元格编辑器。但是我想将JCombobox的选定索引设置为当单击单元格进行编辑时单元格的当前值。我如何做到这一点?在JCombobox中设置选定的索引作为单元编辑器在jtable编辑开始

,我使用的电池,也为JComboBox中的项目类别:

public class PersianLetterIDPair {    
    private int id; 
    private String letter; 

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

    public int getID() 
    { 
     return id; 
    } 

    public String getLetter() 
    { 
     return letter; 
    } 


    public void setID(int inID) 
    { 
     id = inID; 
    } 

    public void setLetter(String inLetter) 
    { 
     letter = inLetter; 
    } 

    public String toString() 
    { 
     return letter; 
    }  

}

我充满了我的JComboBox方式:

Vector<PersianLetterIDPair> model2 = new Vector<PersianLetterIDPair>(); 


         model1 = myDBLayer 
           .getVectorPersianLettersIDContent(); 
         int tPLID; 
         String tPL; 

         Iterator iterator = model1.iterator(); 
         while (iterator.hasNext()) { 

          Vector newRow = new Vector(); 
          newRow = (Vector) iterator.next(); 
          tPLID = (Integer) newRow.get(0); 
          tPL = (String) newRow.get(1); 

          model2.addElement(new PersianLetterIDPair(tPLID, 
            tPL)); 
         } 

         PersianLetters0001 = new JComboBox(model2); 
         jTable2.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(PersianLetters0001)); 

我所用的表型号为我的Jtable如下:

public class FormSimilaritiesTableModel extends AbstractTableModel { 

private DBLayer myDBLayer = new DBLayer(); 
private ResultSet rs; 
private String colNames[]; 
private Vector<FormSimilarityRow> allRows; 
private FormSimilarityRow row; 
private Vector<FormSimilarityRow> newRow; 

private int li_cols; 

private String tableName; 
private ResultSetMetaData myM; 

private Vector<FormSimilarityRow> deletedKeys; 
private Vector newRows; 
private Vector updatedRows; 

private boolean ibRowInserted = false; 
private guiBaseTables myGuiBaseTables ; 
boolean ibRowNew = false; 

FormSimilaritiesTableModel() { 

    deletedKeys = new Vector(); 
    newRows = new Vector(); 
    updatedRows = new Vector(); 
    try { 
     ResultSet rs = myDBLayer.getrsFormSimilarities(); 
     li_cols = 3 ; 
     colNames = new String[li_cols]; 
     colNames[0] = "Persian Letter 1"; 
     colNames[1] = "Persian Letter 2"; 
     colNames[2] = "Form Similarity";    
     allRows = new Vector<FormSimilarityRow>(); 
     int rPLID1; 
     String rPL1; 
     int rPLID2; 
     String rPL2; 
     while (rs.next()) { 
      ///newRow = new Vector(); 
      rPLID1 = (Integer) rs.getObject(1); 
      rPL1 = (String) rs.getObject(2); 

      rPLID2 = (Integer) rs.getObject(3); 
      rPL2 = (String) rs.getObject(4); 


      allRows.addElement(new FormSimilarityRow(new PersianLetterIDPair(rPLID1, rPL1),new PersianLetterIDPair(rPLID2, rPL2), (Integer)rs.getObject(5))); 

     } // while 

    } catch (SQLException e) { 
     System.out.println(e.getMessage()); 
    } 

} 

public Class getColumnClass(int col) { 


     if (col == 0 || col == 1) { 
      return PersianLetterIDPair.class; 
     } else if (col == 2) { 
      return Integer.class; 
     } else { 
      return null; 
     } 
} 

public String getColumnName(int col) {  
    return colNames[col]; 
} 

public int getColumnCount() { 
    return li_cols; 
} 

public int getRowCount() { 
    return allRows.size(); 
} 

public Object getValueAt(int arow, int col) { 
    row = allRows.elementAt(arow); 
    if(col == 0){   
     PersianLetterIDPair pL1 = row.getPL1(); 
     return pL1.getLetter(); 
    } 
    else 
    if(col == 1){   
     PersianLetterIDPair pL2 = row.getPL2(); 
     return pL2.getLetter(); 
    } 
    else{ 
     return row.getFS(); 
    } 

} 

public boolean isCellEditable(int row, int col) { 
    int totalNewRows;     
    if (col == 0 || col == 1) { 
     totalNewRows = newRows.size(); 
     for(int j = 0; j< totalNewRows; j++) 
     { 
      int rVal = ((Integer) newRows.get(j)).intValue();    
      if( rVal == row + 1){ 
       return true; 
      }        
     } 
     return false; 


    } else { 
     return true; 
    } 
} 

public void setValueAt(Object aValue, int aRow, int aCol) {  

    FormSimilarityRow dataRow = allRows.elementAt(aRow); 
    if (aCol == 0){  
     PersianLetterIDPair sV = (PersianLetterIDPair) aValue; 
     dataRow.setPL1(sV); 
    } 
    else 
    if (aCol == 1){  
     PersianLetterIDPair sV = (PersianLetterIDPair) aValue; 
     dataRow.setPL2(sV); 

    } 
    else   
     dataRow.setFS((Integer) aValue); 
    fireTableCellUpdated(aRow, aCol); 
} 
... 

}

和我的JTable的定义为:

myFormSimilaritiesTableModel = new FormSimilaritiesTableModel(); 
         jTable2 = new JTable(); 
         jScrollPane2.setViewportView(jTable2); 
         jTable2.setModel(myFormSimilaritiesTableModel); 
         jTable2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); 
         jTable2.getTableHeader() 
           .setReorderingAllowed(false); 

我改变了getValueAt方法,其通过所述@Polet返回PersianLetterIDPair尖端以下:

public Object getValueAt(int arow, int col) { 
    row = allRows.elementAt(arow); 
    if(col == 0){   
     PersianLetterIDPair pL1 = row.getPL1(); 
     //return pL1.getLetter(); 
     return pL1; 
    } 
    else 
    if(col == 1){   
     PersianLetterIDPair pL2 = row.getPL2(); 
     //return pL2.getLetter(); 
     return pL2; 
    } 
    else{ 
     return row.getFS(); 
    } 

} 

然后我创建TableCellRenderer:

class PersianLetterIDPairRenderer extends DefaultTableCellRenderer 

{

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { 
     super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);  
     setText(((PersianLetterIDPair)value).getLetter());    
     return this; 
    } 

}

然后我添加到我的JTable:

TableColumn tCol = jTable2.getColumnModel().getColumn(0); 
         tCol.setCellRenderer(new PersianLetterIDPairRenderer()); 
         tCol = jTable2.getColumnModel().getColumn(1); 
         tCol.setCellRenderer(new PersianLetterIDPairRenderer()); 

但是,当我从的TableCellRenderer为断开它得到正确的:

TableColumn tCol = jTable2.getColumnModel().getColumn(0); 
         //tCol.setCellRenderer(new PersianLetterIDPairRenderer()); 
         tCol = jTable2.getColumnModel().getColumn(1); 
         //tCol.setCellRenderer(new PersianLetterIDPairRenderer()); 
+0

你可以在getTableCellEditorComponent方法初始化值 – MadProgrammer 2013-03-03 08:29:18

+0

使用[DefaultCellEditor(http://docs.oracle.com/javase/6/docs/api/ javax/swing/DefaultCellEditor.html#DefaultCellEditor%28javax.swing.JComboBox%29),它可以帮助你。 – 2013-03-03 08:32:27

+0

这个值来自XxxTableModel, – mKorbel 2013-03-03 08:32:59

回答

1

看看这个链接Click here

OR

看到这个小例子:

import javax.swing.*; 
import java.awt.*; 
import javax.swing.table.TableColumn; 

public class TableTest extends JFrame { 

    JTable table ; 
    public TableTest(){ 
     table = new JTable(4,2); 
     String []subject = {"Java Programming","Hoshang","Mathematics","Database"}; 
     String []lecturer={"Nuhara","Jon","Saran","Mikey"}; 
     table.setSize(200, 200); 
     JComboBox subj = new JComboBox(subject); 
     JComboBox lec = new JComboBox(lecturer); 

     table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(lec)); 
     table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(subj)); 
     /* 
     * OR you can use TableColumn 
     * 
     */ 
//  TableColumn tc = table.getColumnModel().getColumn(0); 
//  tc.setCellEditor(new DefaultCellEditor(subj)); 


     this.add(new JScrollPane(table),BorderLayout.CENTER); 
     this.setVisible(true); 
     this.setSize(300,200); 
     this.setDefaultCloseOperation(3); 
    } 
    public static void main(String...ag){ 
     new TableTest(); 
    } 
} 
+4

请提供一个真实的答案,这将是可读的广告vitam aeternam,而不仅仅是一个链接。 – 2013-03-03 09:33:27

+0

@JBNizet谢谢,我编辑了答案并发布了一个示例。 – Azad 2013-03-03 11:08:40

+1

谢谢你的回复。我做了同样的事情,但它在我的程序中不起作用。我应该提到我的代码存在差异。我的JComboBox模型不是一个字符串数组,因为我想为JComboBox中的每个项目设置一个隐藏值,我创建了一个保持id和des的类,然后用此类的对象填充我的Jcombobox。另一方面,我的单元格的类与我的tablemodel中提到的类相同。但是每次jcombobox作为单元格编辑器打开时,其选定索引都与点击单元格的当前值不同。 – Leila 2013-03-03 14:54:23

1

至于建议,使用DefaultCellEditorJComboBox

小工作示例展示了这一点:

import java.awt.BorderLayout; 
import java.util.Random; 
import java.util.Vector; 

import javax.swing.DefaultCellEditor; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.SwingUtilities; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.table.DefaultTableModel; 

public class TestTable2 { 

    protected void initUI() { 
     DefaultTableModel model = new DefaultTableModel(); 
     for (int i = 0; i < 3; i++) { 
      model.addColumn("Col-" + (i + 1)); 
     } 
     Random random = new Random(); 
     for (int i = 0; i < 2000; i++) { 
      Vector<Object> row = new Vector<Object>(); 
      for (int j = 0; j < 3; j++) { 
       row.add(VALUES[random.nextInt(VALUES.length)]); 
      } 
      model.addRow(row); 
     } 
     JTable table = new JTable(model); 
     DefaultCellEditor editor = new DefaultCellEditor(new JComboBox(VALUES)); 
     for (int i = 0; i < table.getColumnCount(); i++) { 
      table.getColumnModel().getColumn(i).setCellEditor(editor); 
     } 
     JFrame frame = new JFrame(TestTable2.class.getSimpleName()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JScrollPane scrollpane = new JScrollPane(table); 
     frame.add(scrollpane, BorderLayout.CENTER); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, 
      UnsupportedLookAndFeelException { 
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new TestTable2().initUI(); 
      } 
     }); 
    } 

    private static final String[] VALUES = { "Sun", "Hello", "Sky", "Cloud", "World", "Time", "System", "Computer", "Dummy", "Simple", 
      "Today", "Lorem" }; 

} 
+0

感谢您的回复。我做了同样的事情,但它在我的程序中不起作用。我应该提到我的代码存在差异。我的JComboBox模型不是一个字符串数组,因为我想为JComboBox中的每个项目设置一个隐藏值,我创建了一个保持id和des的类,然后用此类的对象填充我的Jcombobox。另一方面,我的单元格的类与我的tablemodel中提到的类相同。但是每次jcombobox作为单元格编辑器打开时,其选定索引都与点击单元格的当前值不同。 – Leila 2013-03-03 14:55:28

+0

@蕾拉,这是完美的你做到这一点。唯一要确保的是当两个项目相同时,equals方法将返回true。如果您有相同对象的不同实例,那么您可能必须在专用类中重写“equals”,以便在适当时返回“true”。 – 2013-03-03 18:09:00

+0

当equals方法被调用时会发生什么?我添加了它,但JComboBox的行为没有任何区别,当它在cell中作为celleditor打开时,其选定索引位于之前打开和关闭的Jcombobox中选定的索引,在此之前可能位于其他类似的细胞。我能否确切地告诉你发生了什么? – Leila 2013-03-04 06:21:13

相关问题