Swing:从TableModel中捕获exception

我有一个TableModel,如果用户输入无效值,可能会在其setValueAt方法上抛出exception:

 public class MyTableModel extends AbstractTableModel { public void setValueAt(Object value, int rowIndex, int columnIndex) { String valueStr = (String) value; // some basic failure state if(valueStr.length()>5) { throw new ValidationException("Value should have up to 5 characters"); } this.currentValue = valueStr; } } 

问题是: 另一个类如何能够捕获此exception? 它可能会显示弹出消息,或更新状态栏,或将单元格绘制为红色。 无论我选择做什么,我都不认为TableModel应该这样做。

据推测,您正在使用JTable来编辑单元格,以便您可以使用自定义编辑器:

 import java.awt.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.table.*; public class TableFiveCharacterEditor extends DefaultCellEditor { private long lastTime = System.currentTimeMillis(); public TableFiveCharacterEditor() { super( new JTextField() ); } public boolean stopCellEditing() { JTable table = (JTable)getComponent().getParent(); try { String editingValue = (String)getCellEditorValue(); if(editingValue.length() != 5) { JTextField textField = (JTextField)getComponent(); textField.setBorder(new LineBorder(Color.red)); textField.selectAll(); textField.requestFocusInWindow(); JOptionPane.showMessageDialog( table, "Please enter string with 5 letters.", "Alert!",JOptionPane.ERROR_MESSAGE); return false; } } catch(ClassCastException exception) { return false; } return super.stopCellEditing(); } public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column) { Component c = super.getTableCellEditorComponent( table, value, isSelected, row, column); ((JComponent)c).setBorder(new LineBorder(Color.black)); return c; } private static void createAndShowUI() { JTable table = new JTable(5, 5); table.setPreferredScrollableViewportSize(table.getPreferredSize()); JScrollPane scrollPane = new JScrollPane(table); // Use a custom editor TableCellEditor fce = new TableFiveCharacterEditor(); table.setDefaultEditor(Object.class, fce); JFrame frame = new JFrame("Table Five Character Editor"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add( scrollPane ); frame.pack(); frame.setLocationByPlatform( true ); frame.setVisible( true ); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } 

第一种方法是使用Thread.setDefaultUncaughtExceptionHandler

 Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { if(e instanceof ValidationException) { JOptionPane.showConfirmDialog(someframe, e.getMessage()); } } }); 

但我不确定是否有更合适的方法来处理这种情况,比如某种exception监听器。