org.nuiton.jaxx.runtime.swing.JTables Maven / Gradle / Ivy
package org.nuiton.jaxx.runtime.swing;
/*
* #%L
* JAXX :: Runtime
* %%
* Copyright (C) 2008 - 2017 CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.swing.JTable;
/**
* Some usefull methods on {@link JTable}.
*
* Created on 12/4/14.
*
* @author Tony Chemit - [email protected]
* @since 2.18
*/
public class JTables {
/** Logger. */
private static final Log log = LogFactory.getLog(JTables.class);
public static void selectFirstCellOnFirstRowAndStopEditing(JTable table) {
// select first cell
doSelectCell(table, 0, 0);
if (table.isEditing()) {
// but no edit it
table.getCellEditor().stopCellEditing();
}
}
public static void selectFirstCellOnLastRow(JTable table) {
// select first cell
doSelectCell(table, table.getRowCount() - 1, 0);
}
public static void selectFirstCellOnRow(JTable table, int row, boolean stopEdit) {
// select first cell
doSelectCell(table, row, 0);
if (stopEdit && table.isEditing()) {
table.getCellEditor().stopCellEditing();
}
}
public static void doSelectCell(JTable table,
int rowIndex,
int columnIndex) {
int rowCount = table.getRowCount();
if (rowCount == 0) {
// no row, can not selected any cell
if (log.isWarnEnabled()) {
log.warn("No row in table, can not select any cell");
}
return;
}
int columnCount = table.getColumnCount();
if (columnCount == 0) {
// no column, can not selected any cell
if (log.isWarnEnabled()) {
log.warn("No column in table, can not select any cell");
}
return;
}
if (columnIndex > columnCount) {
if (log.isWarnEnabled()) {
log.warn(String.format("ColumnIndex: %s is more than columnCount %s", columnIndex, columnCount));
}
columnIndex = columnCount - 1;
}
if (columnIndex < 0) {
columnIndex = 0;
}
if (rowIndex >= rowCount) {
if (log.isWarnEnabled()) {
log.warn(String.format("RowIndex: %s is more than rowCount %s", rowIndex, rowCount));
}
rowIndex = rowCount - 1;
}
if (rowIndex < 0) {
rowIndex = 0;
}
table.setColumnSelectionInterval(columnIndex, columnIndex);
table.setRowSelectionInterval(rowIndex, rowIndex);
table.editCellAt(rowIndex, columnIndex);
}
}