JTable.setDefaultEditor()无效但设置为特定字段有效。

时间:2015-07-14 01:06:10

标签: java swing jtable tablecelleditor

尝试使用JTable.setDefaultEditor()但它似乎没有激活。 将其专门设置为列可以工作但只是不将其设置为默认编辑器。不返回println命令,但在设置为特定列时可见。

设置默认编辑器时是否需要额外的步骤?

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

    public class Main {
      public static void main(String[] argv) throws Exception {

        JFrame myFrame = new JFrame();
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String columnNames[] = { "Column 1", "Column 2", "Column 3" };

        String dataValues[][] =
        {
                { "12", "234", "67" },
                { "-123", "43", "853" },
                { "93", "89.2", "109" },
                { "279", "9033", "3092" }
            };
        JTable table = new JTable(dataValues, columnNames);
        myFrame.getContentPane().add(table);

        table.setDefaultEditor(String.class, new MyTableCellEditor());
    //    TableColumn col = table.getColumnModel().getColumn(0);
    //    col.setCellEditor(new MyTableCellEditor());
        myFrame.pack();
        myFrame.setVisible(true);
      }
    }

    class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor, FocusListener
    {

        JComponent component = new JTextField();

        public MyTableCellEditor()
        {
             component.addFocusListener(this);  
        }

      public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
          int rowIndex, int vColIndex) {
          System.out.println("Inside getTableCellEditorComponent()");
        ((JTextField) component).setText((String) value);

        return component;
      }

      public Object getCellEditorValue() {
        return ((JTextField) component).getText();
      }

        @Override
        public void focusGained(FocusEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void focusLost(FocusEvent e) {
            System.out.println("Focus Lost");

        }
    }

1 个答案:

答案 0 :(得分:1)

这是我不喜欢DefaultTableModel ...

的原因之一

如果您将table.setDefaultEditor(String.class, new MyTableCellEditor());更改为table.setDefaultEditor(Object.class, new MyTableCellEditor());,它会有效,但更好的解决方案是覆盖getColumnClass

DefaultTableModel方法
DefaultTableModel model = new DefaultTableModel(dataValues, columnNames){

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        // You really should be checking the columnIndex and
        // returning the appropriate data type for the column,
        // but you get the idea
        return String.class;
    }

};
JTable table = new JTable(model);
myFrame.getContentPane().add(table);

table.setDefaultEditor(String.class, new MyTableCellEditor());

请查看How to Use Tables了解详情