1 31 32 package org.antlr.xjlib.appkit.swing; 33 34 import javax.swing.*; 35 import javax.swing.event.ListSelectionEvent ; 36 import javax.swing.event.ListSelectionListener ; 37 import javax.swing.table.DefaultTableModel ; 38 import java.awt.*; 39 import java.awt.dnd.Autoscroll ; 40 41 public class XJTable extends JTable implements Autoscroll { 42 43 private int margin = 12; 44 45 public XJTableDelegate delegate; 46 47 public int selectionRow = -1; 48 public boolean ignoreSelectionEvent = false; 49 50 public boolean allowEmptySelection = true; 51 public boolean rememberSelection = false; 52 public boolean autoresizeColumn = false; 53 54 public XJTable() { 55 super(); 56 init(); 57 } 58 59 public XJTable(DefaultTableModel model) { 60 super(model); 61 init(); 62 } 63 64 public void init() { 65 getSelectionModel().addListSelectionListener(new ListSelectionListener () { 66 public void valueChanged(ListSelectionEvent e) { 67 if(e.getValueIsAdjusting()) 68 return; 69 70 if(!ignoreSelectionEvent) { 71 setSelectedRow(getSelectedRow()); 72 if(delegate != null) 73 delegate.tableSelectionChanged(XJTable.this, selectionRow); 74 } 75 } 76 }); 77 } 78 79 public void setDelegate(XJTableDelegate delegate) { 80 this.delegate = delegate; 81 } 82 83 public void setAllowEmptySelection(boolean flag) { 84 allowEmptySelection = flag; 85 } 86 87 public void setRememberSelection(boolean flag) { 88 rememberSelection = flag; 89 } 90 91 public void setAutoresizeColumn(boolean flag) { 92 autoresizeColumn = flag; 93 } 94 95 public void setSelectedRow(int row) { 96 if(row == -1 && !allowEmptySelection) 97 row = 0; 98 99 selectionRow = Math.min(row, getRowCount()-1); 100 if(selectionRow >= 0) { 101 setRowSelectionInterval(selectionRow, selectionRow); 102 } 103 } 104 105 public void reload() { 106 ignoreSelectionEvent = true; 107 try { 108 DefaultTableModel model = (DefaultTableModel ) getModel(); 109 model.fireTableDataChanged(); 110 111 setSelectedRow(selectionRow); 112 } finally { 113 ignoreSelectionEvent = false; 114 } 115 } 116 117 public Insets getAutoscrollInsets() { 118 Rectangle outer = getBounds(); 119 Rectangle inner = getParent().getBounds(); 120 121 return new Insets(inner.y-outer.y+margin, inner.x-outer.x+margin, 122 outer.height-inner.height+margin, 123 outer.width-inner.width+margin); 124 } 125 126 public void autoscroll(Point point) { 127 int row = rowAtPoint(point); 128 Rectangle outer = getBounds(); 129 Rectangle r2 = getCellRect(point.y+outer.y<=margin?row-1:row+1, 0, true); 130 scrollRectToVisible(r2); 131 } 132 133 public void selectLastRow() { 134 setSelectedRow(getRowCount()-1); 135 scrollRectToVisible(getCellRect(getRowCount()-1, 0, true)); 136 } 137 138 } 139 | Popular Tags |