下面这个例子中要求编辑单元格时输入一个整数,你可以跟据自己的要求改一下stopCellEditing()方法中的判断代码。
public class Test
{
static class MyEditor
extends DefaultCellEditor
{ public MyEditor()
{
super(new JTextField());
} public boolean stopCellEditing()
{
String value = (String) getCellEditorValue();
try {
Integer.parseInt(value);
}
catch (NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
this.editorComponent.requestFocus();
return false;
}
return super.stopCellEditing();
}
} public static void main(String[] args)
{
final JTable table = new JTable(new DefaultTableModel(100, 5));
table.setDefaultEditor(Object.class, new MyEditor());
JScrollPane sp = new JScrollPane(table);
JFrame f = new JFrame();
f.getContentPane().add(sp, BorderLayout.CENTER);
f.setSize(800, 600);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

解决方案 »

  1.   

    public boolean stopCellEditing() {
                String value = (String) getCellEditorValue();
                try
                {
                    Integer.parseInt(value);
                }
                catch (NumberFormatException e)
                {
                    throw new RuntimeException();
                }
                return super.stopCellEditing();
            }我觉得return false改成throw Exception可能更象那么回事
    因为return false后虽然当前单元格还处于编辑状态,但是用鼠标却可以把JTable的selectedRow和selectedColumn换到别的单元格里去
    当然throw Exception也有点问题,因为java.awt.EventDispatchThread会在后台打出一堆Exception
      

  2.   

    public class Test
    {
    static class MyEditor
    extends DefaultCellEditor
    {
    public MyEditor()
    {
    super(new JTextField());
    }

    public boolean stopCellEditing()
    {
    String value = (String) getCellEditorValue();
    try {
    Integer.parseInt(value);
    }
    catch (NumberFormatException e) {
    Toolkit.getDefaultToolkit().beep();
    this.editorComponent.requestFocus();
    return false;
    }
    return super.stopCellEditing();
    }
    } static class MyListSelectionModel extends DefaultListSelectionModel {
    private JTable table = null; public MyListSelectionModel(JTable table)
    {
    this.table = table;
    } public void setSelectionInterval(int index0, int index1)
    {
    if (table.isEditing()) {
    return;
    }
    super.setSelectionInterval(index0, index1);
    }

    public void setLeadSelectionIndex(int leadIndex)
    {
    if (table.isEditing()) {
    return;
    }
    super.setLeadSelectionIndex(leadIndex);
    }
    }

    public static void main(String[] args)
    {
    final JTable table = new JTable(new DefaultTableModel(100, 5));
    table.setDefaultEditor(Object.class, new MyEditor());
    table.setSelectionModel(new MyListSelectionModel(table));
    table.getColumnModel().setSelectionModel(new MyListSelectionModel(table));
    JScrollPane sp = new JScrollPane(table);
    JFrame f = new JFrame();
    f.getContentPane().add(sp, BorderLayout.CENTER);
    f.setSize(800, 600);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    }
    }
      

  3.   

    谢谢gtlang78() 和relive(六道轮回,无想转生),这里我补充一点。我的数据的合法性判断什么的都是在setValueAt()里面进行的。如果按照你们的思路这些判断应该摆在stopCellEditing()中,换句话说能不能在setValueAt()里面进行判断,并且如果是非法的就将这个单元格还是停留在编辑状态,并且光标落在里面。
    谢谢。
      

  4.   


    在setValueAt()里if(不合法)
    throw new RuntimeException();
      

  5.   

    首先,程序将会抛出一堆异常,但这些异常会打在控制台,不会出现在界面上
    其次,这只是个思路,期待问问题的人自己理解和扩展,都写好的有什么意思?tree501(爱之星)应你的要求,把代码写出来吧。。public class BusinessCheckException extends RuntimeException{}public class MyEditor extends DefaultCellEditor{
    public boolean stopCellEditing(){
    try{
        return super.stopCellEditing();
    }
    catch(BusinessCheckException e){
        Toolkit.getDefaultToolkit().beep();
        this.editorComponent.requestFocus();
        return false;
    }

    public class MyTableModel extends AbstractTableModel{
    public void setValueAt(int row,int column){
    if(不合法)
        throw new BusinessCheckException();
    }
    }
    当然,我写这些不是最好的,抛块砖头,有玉的尽管砸过来 ^_^
    还有,我为什么倾向于throw new Exception()?因为如果因为某种原因你Table的CellEditor被替换成不是你写的那个类型的时候,throw new Exception()依然可以达到同样的效果。
      

  6.   

    和你说的动能差不多
    <code>
    public class XTextFieldCellEditor
        extends XTextField
        implements TableCellEditor {  protected EventListenerList listenerList = new EventListenerList();
      protected ChangeEvent changeEvent = new ChangeEvent(this);
      private int _length;
      private Class _classType;
      private final Border DEFAULT_BORDER;
      private JTable _table;  /**
       * 构造方法
       * @param xtext XText 父类
       * @param doc Document
       * @param text String 文本
       * @param columns int 列数
       * @throws Exp
       */
      public XTextFieldCellEditor(XText xtext, Document doc, String text,
                                  int columns,Class classType) throws
          Exp {
        this(xtext, doc, text, columns, XSize2.get(XAbs.DEFAULT),classType);
      }  public XTextFieldCellEditor(XText xtext, Document doc, String text,
                                  int columns,
                                  XSize2 size2,Class classType) throws Exp {
        super(xtext, doc, text, columns, size2);
        this.setBorder(BorderFactory.createEmptyBorder());
        DEFAULT_BORDER = this.getBorder();
        setClassType(classType);
      }  /**
       * 取长度
       * @return int
       */
      public int getLength(){
        return _length;
      }  /**
       * 设置长度
       * @param length int
       */
      public void setLength(int length){
        _length = length;
      }  /**
       * 取数据类型
       * @return Class
       */
      public Class getClassType(){
        return _classType;
      }  /**
       * 设置类型
       * @param classType Class
       */
      public void setClassType(Class classType){
        _classType = classType;
      }  /**
       * 得到焦点事件
       * @param e FocusEvent
       */
      public void focusGained(FocusEvent e) {
         super.focusGained(e);
      }  /**
       * 失去焦点事件
       * @param e FocusEvent
       */
      public void focusLost(FocusEvent e) {
        super.focusLost(e);
      }  /**
       * 置数据
       * @param value Object
       */
      public void setValue(Object value) {
        if (value != null) {
          setText(value.toString());
        }
      }
      
      public void addCellEditorListener(CellEditorListener listener) {
        listenerList.add(CellEditorListener.class, listener);
      }  public void removeCellEditorListener(CellEditorListener listener) {
        listenerList.remove(CellEditorListener.class, listener);
      }  protected void fireEditingStopped() {
        CellEditorListener listener;
        Object[] listeners = listenerList.getListenerList();
        for (int i = 0; i < listeners.length; i++) {
          if (listeners[i] == CellEditorListener.class) {
            listener = (CellEditorListener) listeners[i + 1];
            listener.editingStopped(changeEvent);
          }
        }
      }  protected void fireEditingCanceled() {
        CellEditorListener listener;
        Object[] listeners = listenerList.getListenerList();
        for (int i = 0; i < listeners.length; i++) {
          if (listeners[i] == CellEditorListener.class) {
            listener = (CellEditorListener) listeners[i + 1];
            listener.editingCanceled(changeEvent);
          }
        }
      }  public void cancelCellEditing() {
        fireEditingCanceled();
      }  /**
       * 停止单元编辑
       * @return boolean
       */
      public boolean stopCellEditing() {
        if(checkValue()){
          fireEditingStopped();
          this.setBorder(DEFAULT_BORDER);
          return true;
        }
        this.setBorder(BorderFactory.createLineBorder(Color.red));
        return false;
      }  public boolean isCellEditable(EventObject event) {
        return true;
      }  public boolean shouldSelectCell(EventObject event) {
        return true;
      }  public Object getCellEditorValue() {
        return getText();
      }  public Component getTableCellEditorComponent(JTable table, Object value,
                                                   boolean isSelected, int row,
                                                   int column) {
        _table = table;
        this.setValue(value);
        return this;
      }  /**
       * 数据类型校验//???暂无长度
       * @return boolean 数据是否正确
       */
      public  boolean checkValue(){
        String str = getCellEditorValue().toString();
        try{
          if (_classType == new String().getClass()) { //String类型
            return true;
          }
          if (_classType == new Byte("0").getClass()) { //Byte类型
            Byte.parseByte(str);
            return true;
          }
          if (_classType == new Integer(0).getClass()) { //Integer类型
            Integer.parseInt(str);
            return true;
          }
          if (_classType == new Long("0").getClass()) { //Long类型
            Long.parseLong(str);
            return true;
          }
          if (_classType == new Double("0.0").getClass()){ //Double类型
            Double.parseDouble(str);
            return true;
          }
          if (_classType == new Float("0.0").getClass()){ //Float类型
            Float.parseFloat(str);
            return true;
          }
          if (_classType == new Time(System.currentTimeMillis()).getClass()){ //Time类型
            Time.valueOf(str);
            return true;
          }
          if (_classType == new Timestamp(System.currentTimeMillis()).getClass()){ //Timestamp类型
            Timestamp.valueOf(str);
            return true;
          }
          if (_classType == new java.sql.Date(System.currentTimeMillis()).getClass()){ //Date类型
            java.sql.Date.valueOf(str);
            return true;
          }
        }catch(Exception e){
          return false;
        }
        return true;
      }
    }
    </code>
      

  7.   

    play100(坐天观井) ,把你的XTextField类也共享一下吧,我想向你学习~~
      

  8.   

    sorry 其他相关代码可能涉及到公司机密  --发布会被开除....
    以上代码为个人所写--未构成犯罪,汗!