0

我是Java编程的初学者。我想使用 JComboBox 作为 JTable 中的单元格编辑器。但是我想将 JCombobox 的选定索引设置为单击以进行编辑时单元格的当前值的值。我怎么能做到这一点?

我用于单元格以及 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);

我按照@Polet 所说的提示更改了 getValueAt 方法以返回 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());
4

2 回答 2

1

看看这个链接点击这里

或者

看这个小例子:

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();
    }
}
于 2013-03-03T08:33:54.173 回答
1

按照建议,将DefaultCellEditor与 一起使用JComboBox

证明这一点的小型工作示例:

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

}
于 2013-03-03T13:09:37.297 回答