anyselectiontable.java

来自「使用swing做的熟悉控件使用的DEMO」· Java 代码 · 共 78 行

JAVA
78
字号
import javax.swing.JTable;
import javax.swing.table.TableModel;

/**
  * A JTable which allows any selection of cells.
  * @author Jan-Friedrich Mutter (jmutter@bigfoot.de)
  */
public class AnySelectionTable extends JTable {
  protected TableSelectionModel tableSelectionModel;

  /**
    * Doing almost the same as its parent except
    * creating its own SelectionModel and UI
    */
  public AnySelectionTable() {
    super();
    createDefaultTableSelectionModel();
    setUI(new AnySelectionTableUI());
  }

  /**
    * Doing almost the same as its parent except
    * creating its own SelectionModel and UI
    */
  public AnySelectionTable(TableModel dm) {
    super(dm);
    createDefaultTableSelectionModel();
    setUI(new AnySelectionTableUI());
  }

  /**
    * refers to its TableSelectionModel.
    */
  public boolean isCellSelected(int row, int column) {
    return tableSelectionModel.isSelected(row, convertColumnIndexToModel(column));
  }

  /**
    * Creates a default TableSelectionModel.
    */
  public void createDefaultTableSelectionModel() {
    TableSelectionModel tsm = new TableSelectionModel();
    setTableSelectionModel(tsm);
  }

  /**
    * same intention as setSelectionModel(ListSelectionModel newModel)
    */
  public void setTableSelectionModel(TableSelectionModel newModel) {
    //the TableSelectionModel shouldn't be null
    if (newModel == null) {
      throw new IllegalArgumentException("Cannot set a null TableSelectionModel");
    }

    //save the old Model
    TableSelectionModel oldModel = this.tableSelectionModel;
    //set the new Model
    this.tableSelectionModel = newModel;
    //The model needs to know how many columns are there
    newModel.setColumns(getColumnModel().getColumnCount());
    getModel().addTableModelListener(newModel);

    if (oldModel != null) {
      removePropertyChangeListener(oldModel);
    }
    addPropertyChangeListener(newModel);

    firePropertyChange("tableSelectionModel", oldModel, newModel);
  }

  /**
    * @return the current TableSelectionModel.
    */
  public TableSelectionModel getTableSelectionModel() {
    return tableSelectionModel;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?