简体   繁体   English

如何获取所选单元格(JComboBox)在JTable中的当前位置

[英]how to get current position of selected cell (JComboBox )in JTable

private JPanel contentPane;
private JTable table;
private JComboBox<String> jcbtest;
private DefaultTableModel tablemodel;

    jcbtest=new JComboBox<String>();
    jcbtest.addItem("item1");
    jcbtest.addItem("item2");
    jcbtest.addItem("item3");
    jcbtest.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            int curi=table.getSelectedRow();
            int curj=table.getSelectedColumn();
            JOptionPane.showMessageDialog(null, "actionListener:"+curi+"    "+curj);

        }
    });

    jcbtest.addItemListener(new ItemListener(){
        public void itemStateChanged (ItemEvent e){
            int curi=table.getSelectedRow();
            int curj=table.getSelectedColumn();
            JOptionPane.showMessageDialog(null, "itemstateChanged:"+curi+"  "+curj);               
        }
    });

    table = new JTable();String title[]={"姓名", "部门", "职位"};
    tablemodel=new DefaultTableModel(title, 3);
    table = new JTable(tablemodel){
        private static final long serialVersionUID=1L;
        public boolean isCellEditable( int rowIndex, int columnIndex){
            if( rowIndex == getRowCount() - 1 ){
                DefaultTableModel dtm=(DefaultTableModel)dataModel;
                dtm.addRow(new String[]{"","",""});
            }
            return true;
        }
    };
    table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jcbtest));

    scrollPane.setViewportView(table);

First time to select, it shows no selected cell 第一次选择,它没有显示选定的单元格

After that, it gave me the position of previous operation 之后,它给了我先前操作的位置

How to get current selected cell position? 如何获得当前选定的单元格位置?

Construct a DefaultCellEditor with a JComboBox<String> , as illustrated here , and use it as a cell editor . 构造一个DefaultCellEditorJComboBox<String> ,如图所示在这里 ,并用它作为一个单元编辑器 When applied to an editable cell, each cell's current selection will be stored in the TableModel . 当应用于可编辑单元格时,每个单元格的当前选择将存储在TableModel

What should I do to get the selected-cell's position? 我应该怎么做才能获得所选单元格的位置?

The JComboBox is used only as a cell editor , and it's selection index is meaningless except when in use as an editor. JComboBox 作为一个单元编辑器 ,它的选择指数,除了在使用时作为一个编辑毫无意义。 At all other times, the chosen value in stored in the TableModel . 在所有其他时间,所选值存储在TableModel Given a particular value, you can use the getIndexOf() method of the editor's DefaultComboBoxModel to determine the position it had when in use as an editor. 给定特定值,您可以使用编辑器的DefaultComboBoxModelgetIndexOf()方法来确定用作编辑器时的位置。

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

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