From c0df04fc9907580f19aa31b9f153526ea750809b Mon Sep 17 00:00:00 2001 From: wsbrenk Date: Mon, 4 Nov 2024 19:43:16 +0100 Subject: [PATCH 1/3] Rename .java to .kt --- .../comp/table/{FixedColumnsTable.java => FixedColumnsTable.kt} | 0 .../core/gui/comp/table/{HOTableModel.java => HOTableModel.kt} | 0 ...{PlayerOverviewTableModel.java => PlayerOverviewTableModel.kt} | 0 ...figurationIntParameter.java => HOConfigurationIntParameter.kt} | 0 ...{HOConfigurationParameter.java => HOConfigurationParameter.kt} | 0 .../{PlayerOverviewTable.java => PlayerOverviewTable.kt} | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename src/main/java/core/gui/comp/table/{FixedColumnsTable.java => FixedColumnsTable.kt} (100%) rename src/main/java/core/gui/comp/table/{HOTableModel.java => HOTableModel.kt} (100%) rename src/main/java/core/gui/model/{PlayerOverviewTableModel.java => PlayerOverviewTableModel.kt} (100%) rename src/main/java/core/model/{HOConfigurationIntParameter.java => HOConfigurationIntParameter.kt} (100%) rename src/main/java/core/model/{HOConfigurationParameter.java => HOConfigurationParameter.kt} (100%) rename src/main/java/module/playerOverview/{PlayerOverviewTable.java => PlayerOverviewTable.kt} (100%) diff --git a/src/main/java/core/gui/comp/table/FixedColumnsTable.java b/src/main/java/core/gui/comp/table/FixedColumnsTable.kt similarity index 100% rename from src/main/java/core/gui/comp/table/FixedColumnsTable.java rename to src/main/java/core/gui/comp/table/FixedColumnsTable.kt diff --git a/src/main/java/core/gui/comp/table/HOTableModel.java b/src/main/java/core/gui/comp/table/HOTableModel.kt similarity index 100% rename from src/main/java/core/gui/comp/table/HOTableModel.java rename to src/main/java/core/gui/comp/table/HOTableModel.kt diff --git a/src/main/java/core/gui/model/PlayerOverviewTableModel.java b/src/main/java/core/gui/model/PlayerOverviewTableModel.kt similarity index 100% rename from src/main/java/core/gui/model/PlayerOverviewTableModel.java rename to src/main/java/core/gui/model/PlayerOverviewTableModel.kt diff --git a/src/main/java/core/model/HOConfigurationIntParameter.java b/src/main/java/core/model/HOConfigurationIntParameter.kt similarity index 100% rename from src/main/java/core/model/HOConfigurationIntParameter.java rename to src/main/java/core/model/HOConfigurationIntParameter.kt diff --git a/src/main/java/core/model/HOConfigurationParameter.java b/src/main/java/core/model/HOConfigurationParameter.kt similarity index 100% rename from src/main/java/core/model/HOConfigurationParameter.java rename to src/main/java/core/model/HOConfigurationParameter.kt diff --git a/src/main/java/module/playerOverview/PlayerOverviewTable.java b/src/main/java/module/playerOverview/PlayerOverviewTable.kt similarity index 100% rename from src/main/java/module/playerOverview/PlayerOverviewTable.java rename to src/main/java/module/playerOverview/PlayerOverviewTable.kt From 86a15b6c7bfb78c131015673a9eaa245eb5ce6ea Mon Sep 17 00:00:00 2001 From: wsbrenk Date: Mon, 4 Nov 2024 19:43:16 +0100 Subject: [PATCH 2/3] Porting HOTableModel and others to Kotlin --- src/main/java/core/db/UserColumnsTable.java | 8 +- .../core/gui/comp/table/FixedColumnsTable.kt | 256 +++--- .../java/core/gui/comp/table/HOTableModel.kt | 815 +++++++++--------- .../gui/model/PlayerOverviewTableModel.kt | 359 ++++---- .../core/model/HOConfigurationIntParameter.kt | 22 +- .../core/model/HOConfigurationParameter.kt | 91 +- .../playerOverview/PlayerOverviewTable.kt | 210 +++-- src/main/resources/release_notes.md | 12 +- 8 files changed, 861 insertions(+), 912 deletions(-) diff --git a/src/main/java/core/db/UserColumnsTable.java b/src/main/java/core/db/UserColumnsTable.java index faac86801..b4a98ca12 100644 --- a/src/main/java/core/db/UserColumnsTable.java +++ b/src/main/java/core/db/UserColumnsTable.java @@ -41,18 +41,18 @@ void deleteModel(int modelId) { } void saveModel(HOTableModel model) { - deleteModel(model.getId()); + deleteModel(model.id); UserColumn[] dbcolumns = model.getColumns(); for (int i = 0; i < dbcolumns.length; i++) { - if (model.getId() == 2 && dbcolumns[i].getId() == UserColumnFactory.ID) { + if (model.id == 2 && dbcolumns[i].getId() == UserColumnFactory.ID) { dbcolumns[i].setDisplay(true); // force ID column } if (dbcolumns[i].isDisplay()) { var _userColumn = new _UserColumn(); _userColumn.setModelIndex(i); - _userColumn.setId(model.getId() * 1000 + dbcolumns[i].getId()); + _userColumn.setId(model.id * 1000 + dbcolumns[i].getId()); _userColumn.setPreferredWidth(dbcolumns[i].getPreferredWidth()); _userColumn.setIndex(dbcolumns[i].getIndex()); _userColumn.setSortPriority(dbcolumns[i].getSortPriority()); @@ -76,7 +76,7 @@ void insertDefault(HOTableModel model) { void loadModel(HOTableModel model) { int count = 0; - var userColumns = load(_UserColumn.class, model.getId() * 1000, model.getId() * 1000 + 999); + var userColumns = load(_UserColumn.class, model.id * 1000, model.id * 1000 + 999); if (!userColumns.isEmpty()) { // user may not delete all columns var modelColumns = model.getColumns(); if (model.userCanDisableColumns() && !DBManager.instance().isFirstStart()) { diff --git a/src/main/java/core/gui/comp/table/FixedColumnsTable.kt b/src/main/java/core/gui/comp/table/FixedColumnsTable.kt index 36f96f9d9..237e83d6e 100644 --- a/src/main/java/core/gui/comp/table/FixedColumnsTable.kt +++ b/src/main/java/core/gui/comp/table/FixedColumnsTable.kt @@ -1,53 +1,49 @@ -package core.gui.comp.table; - -import core.gui.comp.renderer.HODefaultTableCellRenderer; -import core.model.HOConfigurationIntParameter; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; -import javax.swing.table.TableModel; -import java.awt.*; -import java.awt.event.AdjustmentListener; +package core.gui.comp.table + +import core.gui.comp.renderer.HODefaultTableCellRenderer +import core.model.HOConfigurationIntParameter +import java.awt.Component +import java.awt.Dimension +import java.awt.event.AdjustmentEvent +import java.awt.event.AdjustmentListener +import java.beans.PropertyChangeEvent +import javax.swing.* +import javax.swing.event.ListSelectionListener +import javax.swing.table.TableCellRenderer +import javax.swing.table.TableColumn +import javax.swing.table.TableModel /** * Table with fixed columns on the left hand side * The other columns can be sorted or disabled by the user */ -public class FixedColumnsTable extends JTable { - +open class FixedColumnsTable @JvmOverloads constructor(tableModel: HOTableModel, fixedColumns: Int = 1) : + JTable(tableModel) { + /** + * Return the number of fixed columns + * @return int + */ /** * Number of fixed columns in table */ - private final int fixedColumns; + val fixedColumnsCount: Int /** * Position of the divider between fixed and scrollable tables */ - private HOConfigurationIntParameter dividerLocation = null; + private var dividerLocation: HOConfigurationIntParameter? = null /** * Fixed table part (left hand side) */ - private final JTable fixed; + private var fixed: JTable? = null /** * Container component for split pane of fixed and scrollable tables */ - private final JScrollPane scrollPane; + private var scrollPane: JScrollPane? = null - /** - * Constructor of table with one fixed columns - * @param tableModel Table model - */ - public FixedColumnsTable(HOTableModel tableModel) { - this(tableModel, 1); - } - /** * Create a fixed columns table * Columns and header tooltips are taken from table model. @@ -57,89 +53,99 @@ public class FixedColumnsTable extends JTable { * @param tableModel Table model * @param fixedColumns fixed columns count */ - public FixedColumnsTable(HOTableModel tableModel, int fixedColumns) { - super(tableModel); - tableModel.table = this; - this.fixedColumns = fixedColumns; + /** + * Constructor of table with one fixed columns + * @param tableModel Table model + */ + init { + tableModel.table = this + this.fixedColumnsCount = fixedColumns // Handle tool tips - final TableCellRenderer header = this.getTableHeader().getDefaultRenderer(); - this.getTableHeader().setDefaultRenderer((table, value, isSelected, hasFocus, row, column) -> { - Component tableCellRendererComponent = header.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - var tableColumn = table.getColumnModel().getColumn(column); - var model = (HOTableModel) table.getModel(); - // Set header tool tip - var tooltipString = model.getDisplayedColumns()[tableColumn.getModelIndex()].getTooltip(); - ((JComponent) tableCellRendererComponent).setToolTipText(tooltipString); - return tableCellRendererComponent; - }); - - setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - setSelectionBackground(HODefaultTableCellRenderer.SELECTION_BG); + val header = getTableHeader().defaultRenderer + getTableHeader().defaultRenderer = + TableCellRenderer { table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int -> + val tableCellRendererComponent = + header.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) + val tableColumn = table.columnModel.getColumn(column) + val model = table.model as HOTableModel + // Set header tool tip + val tooltipString = model.getDisplayedColumns()[tableColumn.modelIndex].getTooltip() + (tableCellRendererComponent as JComponent).toolTipText = tooltipString + tableCellRendererComponent + } + + setAutoResizeMode(AUTO_RESIZE_OFF) + setSelectionMode(ListSelectionModel.SINGLE_SELECTION) + setSelectionBackground(HODefaultTableCellRenderer.SELECTION_BG) if (fixedColumns > 0) { - fixed = new JTable(getModel()); - fixed.setFocusable(false); - fixed.setSelectionModel(getSelectionModel()); - fixed.getTableHeader().setReorderingAllowed(false); - fixed.setSelectionModel(getSelectionModel()); + val fixed = JTable(model) + fixed.isFocusable = false + fixed.selectionModel = getSelectionModel() + fixed.tableHeader.reorderingAllowed = false + fixed.selectionModel = getSelectionModel() // Remove the non-fixed columns from the fixed table - while (fixed.getColumnCount() > fixedColumns) { - var _columnModel = fixed.getColumnModel(); - _columnModel.removeColumn(_columnModel.getColumn(fixedColumns)); + while (fixed.columnCount > fixedColumns) { + val _columnModel = fixed.columnModel + _columnModel.removeColumn(_columnModel.getColumn(fixedColumns)) } + this.fixed = fixed + // Remove the fixed columns from the main table - int width = 0; - int i = 0; - for (; i < fixedColumns; i++) { - var _columnModel = getColumnModel(); - var column = _columnModel.getColumn(0); - width += column.getPreferredWidth(); - _columnModel.removeColumn(column); + var width = 0 + var i = 0 + while (i < fixedColumns) { + val _columnModel = getColumnModel() + val column = _columnModel.getColumn(0) + width += column.preferredWidth + _columnModel.removeColumn(column) + i++ } // Sync scroll bars of both tables - var fixedScrollPane = new JScrollPane(fixed); - var rightScrollPane = new JScrollPane(this); - fixedScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); - rightScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); - final JScrollBar fixedScrollBar = fixedScrollPane.getVerticalScrollBar(); - final JScrollBar rightScrollBar = rightScrollPane.getVerticalScrollBar(); + val fixedScrollPane = JScrollPane(fixed) + val rightScrollPane = JScrollPane(this) + fixedScrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS + rightScrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS + val fixedScrollBar = fixedScrollPane.verticalScrollBar + val rightScrollBar = rightScrollPane.verticalScrollBar // setVisible(false) does not have an effect, so we set the size to // false. We can't disable the scrollbar with VERTICAL_SCROLLBAR_NEVER // because this will disable mouse wheel scrolling. - fixedScrollBar.setPreferredSize(new Dimension(0, 0)); + fixedScrollBar.preferredSize = Dimension(0, 0) // Synchronize vertical scrolling - AdjustmentListener adjustmentListener = e -> { - if (e.getSource() == rightScrollBar) { - fixedScrollBar.setValue(e.getValue()); + val adjustmentListener = AdjustmentListener { e: AdjustmentEvent -> + if (e.source === rightScrollBar) { + fixedScrollBar.value = e.value } else { - rightScrollBar.setValue(e.getValue()); + rightScrollBar.value = e.value } - }; - fixedScrollBar.addAdjustmentListener(adjustmentListener); - rightScrollBar.addAdjustmentListener(adjustmentListener); - rightScrollPane.getVerticalScrollBar().setModel(fixedScrollPane.getVerticalScrollBar().getModel()); - JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, fixedScrollPane, rightScrollPane); - if (width == 0) width = 60; - this.dividerLocation = new HOConfigurationIntParameter("TableDividerLocation_" + tableModel.getId(), width); - splitPane.setDividerLocation(this.dividerLocation.getIntValue()); - splitPane.addPropertyChangeListener(evt -> { - var propertyName = evt.getPropertyName(); - if (propertyName.equals("dividerLocation")) { - var pane = (JSplitPane) evt.getSource(); - dividerLocation.setIntValue(pane.getDividerLocation()); + } + fixedScrollBar.addAdjustmentListener(adjustmentListener) + rightScrollBar.addAdjustmentListener(adjustmentListener) + rightScrollPane.verticalScrollBar.model = fixedScrollPane.verticalScrollBar.model + val splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, fixedScrollPane, rightScrollPane) + if (width == 0) width = 60 + val dividerLocation = HOConfigurationIntParameter("TableDividerLocation_" + tableModel.id, width) + splitPane.dividerLocation = dividerLocation.getIntValue() + splitPane.addPropertyChangeListener { evt: PropertyChangeEvent -> + val propertyName = evt.propertyName + if (propertyName == "dividerLocation") { + val pane = evt.source as JSplitPane + dividerLocation.setIntValue(pane.dividerLocation) } - }); - scrollPane = new JScrollPane(); - scrollPane.setViewportView(splitPane); + } + this.dividerLocation = dividerLocation + val scrollPane = JScrollPane() + scrollPane.setViewportView(splitPane) + this.scrollPane = scrollPane } else { // No fixed columns - fixed = null; - scrollPane = new JScrollPane(this); + fixed = null + scrollPane = JScrollPane(this) } } @@ -148,10 +154,9 @@ public class FixedColumnsTable extends JTable { * @param rowIndex0 one end of the interval * @param rowIndex1 the other end of the interval */ - @Override - public void setRowSelectionInterval(int rowIndex0, int rowIndex1){ - super.setRowSelectionInterval(rowIndex0, rowIndex1); - if ( fixed != null ) fixed.setRowSelectionInterval(rowIndex0, rowIndex1); + override fun setRowSelectionInterval(rowIndex0: Int, rowIndex1: Int) { + super.setRowSelectionInterval(rowIndex0, rowIndex1) + fixed?.setRowSelectionInterval(rowIndex0, rowIndex1) } /** @@ -159,54 +164,41 @@ public class FixedColumnsTable extends JTable { * @param columnClass set the default cell renderer for this columnClass * @param renderer default cell renderer to be used for this columnClass */ - @Override - public void setDefaultRenderer(Class columnClass, TableCellRenderer renderer) { - super.setDefaultRenderer(columnClass, renderer); - if ( fixed != null ) fixed.setDefaultRenderer(columnClass, renderer); + override fun setDefaultRenderer(columnClass: Class<*>?, renderer: TableCellRenderer?) { + super.setDefaultRenderer(columnClass, renderer) + fixed?.setDefaultRenderer(columnClass, renderer) } /** * Add a list selection listener * @param listener ListSelectionListener */ - public void addListSelectionListener(ListSelectionListener listener) { - ListSelectionModel rowSM = getSelectionModel(); - rowSM.addListSelectionListener(listener); + fun addListSelectionListener(listener: ListSelectionListener?) { + val rowSM = getSelectionModel() + rowSM.addListSelectionListener(listener) } /** * Set the row sorter to both internal tables * @param sorter Sorter */ - @Override - public void setRowSorter(RowSorter sorter) { - super.setRowSorter(sorter); - if ( fixed != null ) fixed.setRowSorter(sorter); + override fun setRowSorter(sorter: RowSorter) { + super.setRowSorter(sorter) + if (fixed != null) fixed!!.rowSorter = sorter } - /** - * Return the number of fixed columns - * @return int - */ - public int getFixedColumnsCount() { - return fixedColumns; - } - - /** - * Returns the outer container component of the fixed column table - * @return Component - */ - public Component getContainerComponent() { - return this.scrollPane; - } - - @Override - public TableColumn getColumn(@NotNull Object identifier) { - try { - return super.getColumn(identifier); - } - catch( IllegalArgumentException e ) { - return fixed.getColumn(identifier); + val containerComponent: Component? + /** + * Returns the outer container component of the fixed column table + * @return Component + */ + get() = this.scrollPane + + override fun getColumn(identifier: Any): TableColumn { + return try { + super.getColumn(identifier) + } catch (e: IllegalArgumentException) { + fixed!!.getColumn(identifier) } } @@ -215,8 +207,10 @@ public class FixedColumnsTable extends JTable { * @param i Column index * @return TableColumn */ - public TableColumn getTableColumn(int i) { - if (i= columncount) - displayedColumns[currentIndex].setIndex(columncount - 1); - currentIndex++; - } // column is displayed - } // for - } - return displayedColumns; - } - - /** - * Return count of displayed columns - * - * @return int - */ - private int getDisplayedColumnCount() { - if (displayedColumnsCount == 0) { - for (UserColumn column : columns) { - if (column.isDisplay()) - displayedColumnsCount++; - } - } - return displayedColumnsCount; - } - - /** - * Returns count of displayed columns redundant method, but this is - * overwritten method from AbstractTableModel - */ - @Override - public int getColumnCount() { - return getDisplayedColumnCount(); - } - - /** - * Return value of one table cell - * - * @param row Row number - * @param column Column number - * - * @return Object - */ - @Override - public final Object getValueAt(int row, int column) { - if (m_clData != null && m_clData.length>row) { - return m_clData[row][column]; - } - return null; - } - - /** - * Return row count - * @return int - */ - @Override - public final int getRowCount() { - return (m_clData != null) ? m_clData.length : 0; - } - - /** - * Return class of a table column - * @param columnIndex the column being queried - * @return Class - */ - @Override - public final Class getColumnClass(int columnIndex) { - final Object obj = getValueAt(0, columnIndex); - - if (obj != null) { - return obj.getClass(); - } - - return "".getClass(); - } - - /** - * Return the name of a table column - * @param columnIndex the column being queried - * @return String - */ - @Override - public final String getColumnName(int columnIndex) { - if (getDisplayedColumnCount() > columnIndex) { - return getDisplayedColumns()[columnIndex].getColumnName(); - } - - return null; - } - - /** - * Set the value of a table cell - * @param value value to assign to cell - * @param row row of cell - * @param column column of cell - */ - @Override - public void setValueAt(Object value, int row, int column) { - m_clData[row][column] = value; - fireTableCellUpdated(table.convertRowIndexToView(row),table.convertColumnIndexToView(column)); - } - - /** - * Abstract init data method has to be provided by subclass - */ - protected abstract void initData(); - - /** - * Return the array index from a Column id - */ - public int getPositionInArray(int searchid) { - final UserColumn[] tmpColumns = getDisplayedColumns(); - for (int i = 0; i < tmpColumns.length; i++) { - if (tmpColumns[i].getId() == searchid) - return i; - } - return -1; - } - - /** - * Get the table column width and index from user column settings stored in the database - * - * @param table Table - */ - private void getUserColumnSettings(JTable table) { - // Restore column order and width settings - Arrays.stream(getDisplayedColumns()) - .sorted(Comparator.comparingInt(UserColumn::getIndex)) - .forEach(i -> getColumnSettings(i, table)); - } - - /** - * Get column order and width from user column - * - * @param userColumn User column holding user's settings - * @param table Table object - */ - private void getColumnSettings(UserColumn userColumn, JTable table) { - var viewColumn = table.getColumn(userColumn.getId()); - viewColumn.setPreferredWidth(userColumn.getPreferredWidth()); - moveColumn(table, userColumn); - } - - private void moveColumn(JTable table, UserColumn userColumn) { - if (table instanceof FixedColumnsTable fixedColumnsTable) { - var targetIndex = userColumn.getIndex() - fixedColumnsTable.getFixedColumnsCount(); - if (targetIndex > 0) { - var index = fixedColumnsTable.getColumnModel().getColumnIndex(userColumn.getId()); - if (index != targetIndex) { - table.moveColumn(index, targetIndex); - } - } - } else { - var index = table.getColumnModel().getColumnIndex(userColumn.getId()); - if (index != userColumn.getIndex()) { - table.moveColumn(index, max(0, userColumn.getIndex())); - } - } - } - - /** - * Set user column settings from the table instance - * @param table Table object - * @return True if one user setting is changed - * False, if no user settings are changed - */ - private boolean setUserColumnSettings(JTable table) { - boolean changed = false; - for (int index = 0; index < table.getColumnCount(); index++) { - var tableColumn = getTableColumn(table, index); - var modelColumn = this.columns[tableColumn.getModelIndex()]; - - if (!modelColumn.isDisplay()) { - modelColumn.setDisplay(true); - changed = true; - } - if (modelColumn.getIndex() != index) { - changed = true; - modelColumn.setIndex(index); - } - - var tableColumnWidth = tableColumn.getWidth(); - if (modelColumn.getPreferredWidth() != tableColumnWidth) { - changed = true; - modelColumn.setPreferredWidth(tableColumnWidth); - } - } - return changed; - } - - /** - * User can disable columns - * @return boolean - */ - public boolean userCanDisableColumns() { - return true; - } - - /** - * Initialize the table object with data from the model - * Todo: Think about making HOTableModel supporting only FixedColumnsTable (JTable==FixedColumnsTable(0 fixed columns)) - * @param table Table object - */ - public void initTable(JTable table) { - this.table = table; - if ( !(table instanceof FixedColumnsTable)) { - var columnModel = table.getColumnModel(); - ToolTipHeader header = new ToolTipHeader(columnModel); - header.setToolTipStrings(getTooltips()); - header.setToolTipText(""); - table.setTableHeader(header); - table.setModel(this); - } - - // Copy user columns' identifiers to table's columns - var displayedColumns = getDisplayedColumns(); - for (int i=0; i(this); - getRowOrderSettings(rowSorter); - table.setRowSorter(rowSorter); - table.setDefaultRenderer(Object.class, new HODefaultTableCellRenderer()); - } - - private TableColumn getTableColumn(JTable table, int i) { - if ( table instanceof FixedColumnsTable fixedColumnstable) { return fixedColumnstable.getTableColumn(i); } - return table.getColumnModel().getColumn(i); - } - - /** - * Store user table settings in the database if they were changed by the user - */ - public void storeUserSettings(){ - if (table == null) return; - var changed = setUserColumnSettings(table); - - RowSorter sorter = (RowSorter) table.getRowSorter(); - if (sorter != null){ - if ( setRowOrderSettings(sorter) ) { - changed = true; - } - } - if (changed){ - DBManager.instance().saveHOColumnModel(this); - } - } - - /** - * Get row order from user columns and restore it to the given row sorter - * - * @param rowSorter Row sorter - */ - private void getRowOrderSettings(RowSorter rowSorter) { - // Restore row order setting - var sortKeys = new ArrayList(); - var sortColumns = Arrays.stream(this.columns).filter(i->i.sortPriority != null).sorted(Comparator.comparingInt(UserColumn::getSortPriority)).toList(); - if (!sortColumns.isEmpty()) { - var userColumns = Arrays.stream(this.columns).toList(); - for (var col : sortColumns) { - var index = userColumns.indexOf(col); - var sortKey = new RowSorter.SortKey(index, col.getSortOrder()); - sortKeys.add(sortKey); - } - } - rowSorter.setSortKeys(sortKeys); - } - - /** - * Set user columns sort priority and order from given row sorter - * @param sorter Row sorter - * @return True if one user setting is changed - * False, if no user settings are changed - */ - private boolean setRowOrderSettings(RowSorter sorter) { - var changed = false; - var rowSortKeys = sorter.getSortKeys(); - for (int i = 0; i < this.columns.length; i++) { - int finalI = i; - var rowSortKey = rowSortKeys.stream().filter(k -> k.getColumn() == finalI).findFirst(); - var userColumn = this.columns[i]; - if (rowSortKey.isPresent() && rowSortKey.get().getSortOrder() != SortOrder.UNSORTED) { - var k = rowSortKey.get(); - var priority = rowSortKeys.indexOf(k); - if (userColumn.getSortPriority() == null || !userColumn.getSortPriority().equals(priority) || - !userColumn.getSortOrder().equals(k.getSortOrder())) { - userColumn.setSortOrder(k.getSortOrder()); - userColumn.setSortPriority(priority); - changed = true; - } - } else if (userColumn.getSortPriority() != null) { - userColumn.setSortPriority(null); - userColumn.setSortOrder(null); - changed = true; - } - } - return changed; - } +abstract class HOTableModel protected constructor( + id: ColumnModelId, + /** Name of the column model, shows in OptionsPanel */ + private val name: String +) : AbstractTableModel() { + /** + * Return model's id + * @return id + */ + /** + * Identifier of the column model. + * It is used for saving columns in db + */ + @JvmField + val id: Int = id.value + + /** Count of displayed column */ + private var displayedColumnsCount = 0 + + /** + * Return all columns of the model + * + * @return UserColumn[] + */ + /** All columns of this model */ + lateinit var columns: Array + protected set + + /** Only displayed columns */ + private var _displayedColumns: Array? = null + + /** Data of table */ + @JvmField + protected var m_clData: Array>? = null + + /** Table component */ + @JvmField + var table: JTable? = null + + /** + * Return the language dependent name of this model + */ + override fun toString(): String { + return TranslationFacility.tr(name) + } + + val columnNames: Array + /** + * Return all column names of displayed columns + * + * @return String[] + */ + get() { + val columnNames = + arrayOfNulls(displayedColumnCount) + for (i in getDisplayedColumns().indices) columnNames[i] = getDisplayedColumns()[i]!!.getColumnName() + return columnNames + } + + val tooltips: Array + /** + * Return all tooltips of displayed columns + * + * @return String[] + */ + get() { + val tooltips = arrayOfNulls(displayedColumnCount) + for (i in getDisplayedColumns().indices) tooltips[i] = getDisplayedColumns()[i]!!.getTooltip() + return tooltips + } + + /** + * Return all displayed columns + * + * @return UserColumn[] + */ + fun getDisplayedColumns(): Array { + if (_displayedColumns == null) { + val displayedColumnsList = ArrayList() + for (column in columns) { + if (column.isDisplay) { + displayedColumnsList.add(column) + } // column is displayed + } // for + _displayedColumns = displayedColumnsList.toTypedArray() + } + return _displayedColumns as Array + } + + private val displayedColumnCount: Int + /** + * Return count of displayed columns + * + * @return int + */ + get() { + if (displayedColumnsCount == 0) { + for (column in columns) { + if (column.isDisplay) displayedColumnsCount++ + } + } + return displayedColumnsCount + } + + /** + * Returns count of displayed columns redundant method, but this is + * overwritten method from AbstractTableModel + */ + override fun getColumnCount(): Int { + return displayedColumnCount + } + + /** + * Return value of one table cell + * + * @param row Row number + * @param column Column number + * + * @return Object + */ + override fun getValueAt(row: Int, column: Int): Any? { + if (m_clData != null && m_clData!!.size > row) { + return m_clData!![row][column] + } + return null + } + + /** + * Return row count + * @return int + */ + override fun getRowCount(): Int { + return if ((m_clData != null)) m_clData!!.size else 0 + } + + /** + * Return class of a table column + * @param columnIndex the column being queried + * @return Class?> + */ + override fun getColumnClass(columnIndex: Int): Class<*> { + val obj = getValueAt(0, columnIndex) + + if (obj != null) { + return obj.javaClass + } + + return "".javaClass + } + + /** + * Return the name of a table column + * @param columnIndex the column being queried + * @return String + */ + override fun getColumnName(columnIndex: Int): String? { + if (displayedColumnCount > columnIndex) { + return getDisplayedColumns()[columnIndex]!!.getColumnName() + } + + return null + } + + /** + * Set the value of a table cell + * @param value value to assign to cell + * @param row row of cell + * @param column column of cell + */ + override fun setValueAt(value: Any, row: Int, column: Int) { + m_clData!![row][column] = value + fireTableCellUpdated(table!!.convertRowIndexToView(row), table!!.convertColumnIndexToView(column)) + } + + /** + * Abstract init data method has to be provided by subclass + */ + protected abstract fun initData() + + /** + * Return the array index from a Column id + */ + fun getPositionInArray(searchid: Int): Int { + val tmpColumns = getDisplayedColumns() + for (i in tmpColumns.indices) { + if (tmpColumns[i]!!.getId() == searchid) return i + } + return -1 + } + + /** + * Get the table column width and index from user column settings stored in the database + * + * @param table Table + */ + private fun getUserColumnSettings(table: JTable) { + // Restore column order and width settings + Arrays.stream(getDisplayedColumns()) + .sorted(Comparator.comparingInt { obj: UserColumn? -> obj!!.getIndex() }) + .forEach { i: UserColumn -> getColumnSettings(i, table) } + } + + /** + * Get column order and width from user column + * + * @param userColumn User column holding user's settings + * @param table Table object + */ + private fun getColumnSettings(userColumn: UserColumn, table: JTable) { + val viewColumn = table.getColumn(userColumn.getId()) + viewColumn.preferredWidth = userColumn.getPreferredWidth() + moveColumn(table, userColumn) + } + + private fun moveColumn(table: JTable, userColumn: UserColumn) { + if (table is FixedColumnsTable) { + val targetIndex = userColumn.getIndex() - table.fixedColumnsCount + if (targetIndex > 0) { + val index = table.getColumnModel().getColumnIndex(userColumn.getId()) + if (index != targetIndex) { + table.moveColumn(index, targetIndex) + } + } + } else { + val index = table.columnModel.getColumnIndex(userColumn.getId()) + if (index != userColumn.getIndex()) { + table.moveColumn(index, max(0.0, userColumn.getIndex().toDouble()).toInt()) + } + } + } + + /** + * Set user column settings from the table instance + * @param table Table object + * @return True if one user setting is changed + * False, if no user settings are changed + */ + private fun setUserColumnSettings(table: JTable): Boolean { + var changed = false + for (index in 0 until table.columnCount) { + val tableColumn = getTableColumn(table, index) + val modelColumn = columns[tableColumn.modelIndex] + + if (!modelColumn.isDisplay) { + modelColumn.isDisplay = true + changed = true + } + if (modelColumn.getIndex() != index) { + changed = true + modelColumn.setIndex(index) + } + + val tableColumnWidth = tableColumn.width + if (modelColumn.getPreferredWidth() != tableColumnWidth) { + changed = true + modelColumn.setPreferredWidth(tableColumnWidth) + } + } + return changed + } + + /** + * User can disable columns + * @return boolean + */ + fun userCanDisableColumns(): Boolean { + return true + } + + /** + * Initialize the table object with data from the model + * Todo: Think about making HOTableModel supporting only FixedColumnsTable (JTable==FixedColumnsTable(0 fixed columns)) + * @param table Table object + */ + fun initTable(table: JTable) { + this.table = table + if (table !is FixedColumnsTable) { + val columnModel = table.columnModel + val header = ToolTipHeader(columnModel) + header.setToolTipStrings(tooltips) + header.toolTipText = "" + table.tableHeader = header + table.model = this + } + + // Copy user columns' identifiers to table's columns + val displayedColumns = getDisplayedColumns() + for (i in 0 until displayedColumnsCount) { + val userColumn = displayedColumns[i] + val tableColumn = getTableColumn(table, i) + tableColumn.identifier = userColumn!!.getId() + } + getUserColumnSettings(table) + val rowSorter = TableRowSorter(this) + getRowOrderSettings(rowSorter) + table.rowSorter = rowSorter + table.setDefaultRenderer(Any::class.java, HODefaultTableCellRenderer()) + } + + private fun getTableColumn(table: JTable, i: Int): TableColumn { + if (table is FixedColumnsTable) { + return table.getTableColumn(i) + } + return table.columnModel.getColumn(i) + } + + /** + * Store user table settings in the database if they were changed by the user + */ + fun storeUserSettings() { + if (table == null) return + var changed = setUserColumnSettings(table!!) + + val sorter = table!!.rowSorter as RowSorter + if (sorter != null) { + if (setRowOrderSettings(sorter)) { + changed = true + } + } + if (changed) { + DBManager.instance().saveHOColumnModel(this) + } + } + + /** + * Get row order from user columns and restore it to the given row sorter + * + * @param rowSorter Row sorter + */ + private fun getRowOrderSettings(rowSorter: RowSorter) { + // Restore row order setting + val sortKeys = ArrayList() + val sortColumns = Arrays.stream(this.columns).filter { i: UserColumn -> i.sortPriority != null }.sorted( + Comparator.comparingInt { obj: UserColumn -> obj.getSortPriority() }).toList() + if (!sortColumns.isEmpty()) { + val userColumns = Arrays.stream(this.columns).toList() + for (col in sortColumns) { + val index = userColumns.indexOf(col) + val sortKey = RowSorter.SortKey(index, col.getSortOrder()) + sortKeys.add(sortKey) + } + } + rowSorter.sortKeys = sortKeys + } + + /** + * Set user columns sort priority and order from given row sorter + * @param sorter Row sorter + * @return True if one user setting is changed + * False, if no user settings are changed + */ + private fun setRowOrderSettings(sorter: RowSorter): Boolean { + var changed = false + val rowSortKeys = sorter.sortKeys + for (i in columns.indices) { + val finalI = i + val rowSortKey = rowSortKeys.stream().filter { k: RowSorter.SortKey -> k.column == finalI }.findFirst() + val userColumn = columns[i] + if (rowSortKey.isPresent && rowSortKey.get().sortOrder != SortOrder.UNSORTED) { + val k = rowSortKey.get() + val priority = rowSortKeys.indexOf(k) + if (userColumn.getSortPriority() == null || userColumn.getSortPriority() != priority || userColumn.getSortOrder() != k.sortOrder) { + userColumn.setSortOrder(k.sortOrder) + userColumn.setSortPriority(priority) + changed = true + } + } else if (userColumn.getSortPriority() != null) { + userColumn.setSortPriority(null) + userColumn.setSortOrder(null) + changed = true + } + } + return changed + } + + companion object { + @Serial + private val serialVersionUID = -207230110294902139L + } } \ No newline at end of file diff --git a/src/main/java/core/gui/model/PlayerOverviewTableModel.kt b/src/main/java/core/gui/model/PlayerOverviewTableModel.kt index d419f7152..33bd624d3 100644 --- a/src/main/java/core/gui/model/PlayerOverviewTableModel.kt +++ b/src/main/java/core/gui/model/PlayerOverviewTableModel.kt @@ -1,16 +1,14 @@ -package core.gui.model; - -import core.db.DBManager; -import core.gui.comp.table.BooleanColumn; -import core.gui.comp.table.HOTableModel; -import core.gui.comp.table.UserColumn; -import core.model.player.Player; -import core.util.HODateTime; -import module.playerOverview.SpielerTrainingsVergleichsPanel; - -import java.io.Serial; -import java.util.List; - +package core.gui.model + +import core.db.DBManager +import core.gui.comp.table.BooleanColumn +import core.gui.comp.table.HOTableModel +import core.gui.comp.table.UserColumn +import core.gui.model.UserColumnController.ColumnModelId +import core.model.player.Player +import core.util.HODateTime +import module.playerOverview.SpielerTrainingsVergleichsPanel +import java.io.Serial /** * Model used to display players in the Squad table. @@ -18,215 +16,208 @@ import java.util.List; * @author Thorsten Dietz * @since 1.36 */ -public class PlayerOverviewTableModel extends HOTableModel { - - @Serial - private static final long serialVersionUID = 5149408240369536138L; - - /** all players **/ - private List m_vPlayers; - - /** - * constructor - * - */ - PlayerOverviewTableModel(UserColumnController.ColumnModelId id){ - this(id,"Spieleruebersicht"); - } - - protected PlayerOverviewTableModel(UserColumnController.ColumnModelId id, String name){ - super(id, name); - initialize(); - } - - /** - * initialize all columns. - */ - private void initialize() { - UserColumn[] basic = UserColumnFactory.createPlayerBasicArray(); - columns = new UserColumn[64]; - columns[0] = basic[0]; - columns[48] = basic[1]; - - UserColumn[] skills = UserColumnFactory.createPlayerSkillArray(); - int skillIndex = 9; // - 20 - System.arraycopy(skills, 0, columns, skillIndex, skills.length); - - UserColumn[] positions = UserColumnFactory.createPlayerPositionArray(); - int positionIndex = 23;//- 41 - System.arraycopy(positions, 0, columns, positionIndex, positions.length); - - UserColumn[] goals = UserColumnFactory.createGoalsColumnsArray(); - int goalsIndex = 42;//-46 - System.arraycopy(goals, 0, columns, goalsIndex, goals.length); - UserColumn[] additionalArray = UserColumnFactory.createPlayerAdditionalArray(); - columns[1] = additionalArray[0]; - columns[2] = additionalArray[1]; - columns[4] = additionalArray[2]; - columns[21] = additionalArray[3]; // best position - columns[5] = additionalArray[4]; - columns[6] = additionalArray[5]; - columns[7] = additionalArray[6]; - columns[58] = additionalArray[7]; - columns[8] = additionalArray[8];// tsi - columns[22] = additionalArray[9]; // lastmatch - columns[47] = additionalArray[11]; - columns[3] = additionalArray[12];// Motherclub - columns[49] = additionalArray[10]; - columns[50] = additionalArray[16]; - columns[51] = additionalArray[17]; - columns[52] = additionalArray[18]; - columns[53] = additionalArray[13]; - columns[54] = additionalArray[14]; - columns[55] = additionalArray[15]; - columns[56] = additionalArray[19]; - columns[57] = additionalArray[20]; - columns[59] = additionalArray[21]; - columns[60] = additionalArray[22]; - columns[61] = additionalArray[23]; // schum-rank - columns[62] = additionalArray[24]; // schum-rank benchmark - columns[63] = new BooleanColumn(UserColumnFactory.AUTO_LINEUP, " ", "AutoAufstellung", 28); - } - - @Override - public final boolean isCellEditable(int row, int col) { - return getValueAt(row, col) instanceof Boolean; - } - - public int getRowIndexOfPlayer(int playerId){ - var modelIndex = getPlayerIndex(playerId); - if (modelIndex > -1){ - return this.table.convertRowIndexToView(modelIndex); - } - return -1; - } - - public Player getPlayerAtRow(int tableRow) { - if (tableRow > -1 ) return m_vPlayers.get(this.table.convertRowIndexToModel(tableRow)); - return null; - } - - public Player getPlayer(int playerId) { +class PlayerOverviewTableModel(id: ColumnModelId, name: String) : HOTableModel(id, name) { + /** all players */ + var players: List? = null + private set + + /** + * constructor + * + */ + internal constructor(id: ColumnModelId) : this(id, "Spieleruebersicht") + + init { + val basic: Array? = UserColumnFactory.createPlayerBasicArray() + val columns : Array = arrayOfNulls(64) + columns[0] = basic?.get(0) + columns[48] = basic?.get(1) + + val skills: Array? = UserColumnFactory.createPlayerSkillArray() + val skillIndex = 9 // - 20 + if (skills != null) { + System.arraycopy(skills, 0, columns, skillIndex, skills.size) + } + + val positions: Array? = UserColumnFactory.createPlayerPositionArray() + val positionIndex = 23 //- 41 + if (positions != null) { + System.arraycopy(positions, 0, columns, positionIndex, positions.size) + } + + val goals: Array? = UserColumnFactory.createGoalsColumnsArray() + val goalsIndex = 42 //-46 + if (goals != null) { + System.arraycopy(goals, 0, columns, goalsIndex, goals.size) + } + val additionalArray: Array? = UserColumnFactory.createPlayerAdditionalArray() + columns[1] = additionalArray?.get(0) + columns[2] = additionalArray?.get(1) + columns[4] = additionalArray?.get(2) + columns[21] = additionalArray?.get(3) // best position + columns[5] = additionalArray?.get(4) + columns[6] = additionalArray?.get(5) + columns[7] = additionalArray?.get(6) + columns[58] = additionalArray?.get(7) + columns[8] = additionalArray?.get(8) // tsi + columns[22] = additionalArray?.get(9) // lastmatch + columns[47] = additionalArray?.get(11) + columns[3] = additionalArray?.get(12) // Motherclub + columns[49] = additionalArray?.get(10) + columns[50] = additionalArray?.get(16) + columns[51] = additionalArray?.get(17) + columns[52] = additionalArray?.get(18) + columns[53] = additionalArray?.get(13) + columns[54] = additionalArray?.get(14) + columns[55] = additionalArray?.get(15) + columns[56] = additionalArray?.get(19) + columns[57] = additionalArray?.get(20) + columns[59] = additionalArray?.get(21) + columns[60] = additionalArray?.get(22) + columns[61] = additionalArray?.get(23) // schum-rank + columns[62] = additionalArray?.get(24) // schum-rank benchmark + columns[63] = BooleanColumn(UserColumnFactory.AUTO_LINEUP, " ", "AutoAufstellung", 28) + + this.columns = columns.filterNotNull().toTypedArray() + assert(this.columns.size == columns.size) + } + + override fun isCellEditable(row: Int, col: Int): Boolean { + return getValueAt(row, col) is Boolean + } + + fun getRowIndexOfPlayer(playerId: Int): Int { + val modelIndex = getPlayerIndex(playerId) + if (modelIndex > -1) { + return table!!.convertRowIndexToView(modelIndex) + } + return -1 + } + + fun getPlayerAtRow(tableRow: Int): Player? { + if (tableRow > -1) return players!![table!!.convertRowIndexToModel(tableRow)] + return null + } + + fun getPlayer(playerId: Int): Player? { // Can be negative for temp player if (playerId != 0) { - for (Player m_vPlayer : m_vPlayers) { - if (m_vPlayer.getPlayerId() == playerId) { - return m_vPlayer; - } - } + for (m_vPlayer in players!!) { + if (m_vPlayer.playerId == playerId) { + return m_vPlayer + } + } } - return null; + return null } - public int getPlayerIndex(int playerId){ - int i = 0; - for (Player m_vPlayer : m_vPlayers) { - if (m_vPlayer.getPlayerId() == playerId) { - return i; - } - i++; - } - return -1; - } - - public List getPlayers() { - return m_vPlayers; - } + fun getPlayerIndex(playerId: Int): Int { + var i = 0 + for (m_vPlayer in players!!) { + if (m_vPlayer.playerId == playerId) { + return i + } + i++ + } + return -1 + } /** * Sets the new list of players. */ - public void setValues(List player) { - m_vPlayers = player; - initData(); + fun setValues(player: List?) { + players = player + initData() } /** * Resets the data for an HRF comparison. */ - public void reInitDataHRFComparison() { - initData(); + fun reInitDataHRFComparison() { + initData() } /** - * Returns the {@link Player} with the same ID as the instance passed, or null. + * Returns the [Player] with the same ID as the instance passed, or `null`. */ - private Player getPreviousPlayerDevelopmentStage(Player currentDevelopmentStage) { - final int id = currentDevelopmentStage.getPlayerId(); + private fun getPreviousPlayerDevelopmentStage(currentDevelopmentStage: Player): Player? { + val id = currentDevelopmentStage.playerId - List selectedPlayerDevelopmentStage = SpielerTrainingsVergleichsPanel.getSelectedPlayerDevelopmentStage(); - for (int i = 0; (selectedPlayerDevelopmentStage != null) && (i < selectedPlayerDevelopmentStage.size()); i++) { - final Player selectedDevelopmentStage = selectedPlayerDevelopmentStage.get(i); + val selectedPlayerDevelopmentStage = SpielerTrainingsVergleichsPanel.getSelectedPlayerDevelopmentStage() + var i = 0 + while ((selectedPlayerDevelopmentStage != null) && (i < selectedPlayerDevelopmentStage.size)) { + val selectedDevelopmentStage = selectedPlayerDevelopmentStage[i] - if (selectedDevelopmentStage.getPlayerId() == id) { - return selectedDevelopmentStage; + if (selectedDevelopmentStage.playerId == id) { + return selectedDevelopmentStage } + i++ } - if (SpielerTrainingsVergleichsPanel.isDevelopmentStageSelected()) { - var hrf = SpielerTrainingsVergleichsPanel.getSelectedHrfId(); - return getFirstPlayerDevelopmentStageAfterSelected(currentDevelopmentStage, hrf); + if (SpielerTrainingsVergleichsPanel.isDevelopmentStageSelected()) { + val hrf = SpielerTrainingsVergleichsPanel.getSelectedHrfId() + return getFirstPlayerDevelopmentStageAfterSelected(currentDevelopmentStage, hrf) } - return null; + return null } /** - * Returns the {@link Player} from the first HRF in which he appears. + * Returns the [Player] from the first HRF in which he appears. */ - private Player getFirstPlayerDevelopmentStageAfterSelected(Player vorlage, Integer hrfId) { - HODateTime after = null; - if (hrfId != null) { - var hrf = DBManager.instance().loadHRF(hrfId); - if (hrf != null) { - after = hrf.getDatum(); - } - } - return core.db.DBManager.instance().loadPlayerFirstHRF(vorlage.getPlayerId(), after); - } + private fun getFirstPlayerDevelopmentStageAfterSelected(vorlage: Player, hrfId: Int?): Player { + var after: HODateTime? = null + if (hrfId != null) { + val hrf = DBManager.instance().loadHRF(hrfId) + if (hrf != null) { + after = hrf.datum + } + } + return DBManager.instance().loadPlayerFirstHRF(vorlage.playerId, after) + } /** * create a data[][] from player-Vector */ - @Override - protected void initData() { - UserColumn[] tmpDisplayedColumns = getDisplayedColumns(); - m_clData = new Object[m_vPlayers.size()][tmpDisplayedColumns.length]; - - for (int i = 0; i < m_vPlayers.size(); i++) { - final Player currentPlayer = m_vPlayers.get(i); - final Player comparisonPlayer = getPreviousPlayerDevelopmentStage(currentPlayer); - for (int j = 0; j < tmpDisplayedColumns.length; j++) { - if (tmpDisplayedColumns[j] instanceof PlayerColumn) { - m_clData[i][j] = ((PlayerColumn) tmpDisplayedColumns[j]).getTableEntry(currentPlayer, comparisonPlayer); - } else if (tmpDisplayedColumns[j] instanceof BooleanColumn) { - m_clData[i][j] = ((BooleanColumn) tmpDisplayedColumns[j]).getValue(currentPlayer); - } - } - } - fireTableDataChanged(); - } + override fun initData() { + val tmpDisplayedColumns = getDisplayedColumns() + m_clData = Array(players!!.size) { arrayOfNulls(tmpDisplayedColumns.size) } + + for (i in players!!.indices) { + val currentPlayer = players!![i] + val comparisonPlayer = getPreviousPlayerDevelopmentStage(currentPlayer) + for (j in tmpDisplayedColumns.indices) { + if (tmpDisplayedColumns[j] is PlayerColumn) { + m_clData!!.get(i)[j] = (tmpDisplayedColumns[j] as PlayerColumn).getTableEntry(currentPlayer, comparisonPlayer) + } else if (tmpDisplayedColumns[j] is BooleanColumn) { + m_clData!!.get(i)[j] = (tmpDisplayedColumns[j] as BooleanColumn).getValue(currentPlayer) + } + } + } + + fireTableDataChanged() + } /** * Initializes the lineup only */ - public void reInitData() { - UserColumn [] tmpDisplayedColumns = getDisplayedColumns(); - for (int i = 0; i < m_vPlayers.size(); i++) { - final Player currentPlayer = m_vPlayers.get(i); - - for (int j = 0; j < tmpDisplayedColumns.length; j++) { - if(tmpDisplayedColumns[j].getId() == UserColumnFactory.NAME - || tmpDisplayedColumns[j].getId() == UserColumnFactory.LINEUP - || tmpDisplayedColumns[j].getId() == UserColumnFactory.BEST_POSITION - || tmpDisplayedColumns[j].getId() == UserColumnFactory.SCHUM_RANK_BENCHMARK - || tmpDisplayedColumns[j].getId() == UserColumnFactory.GROUP){ - m_clData[i][j] = ((PlayerColumn)tmpDisplayedColumns[j]).getTableEntry(currentPlayer,null); - } else if (tmpDisplayedColumns[j].getId() == UserColumnFactory.AUTO_LINEUP) { - m_clData[i][j] = ((BooleanColumn) tmpDisplayedColumns[j]).getValue(currentPlayer); - } - } + fun reInitData() { + val tmpDisplayedColumns = getDisplayedColumns() + for (i in players!!.indices) { + val currentPlayer = players!![i] + for (j in tmpDisplayedColumns.indices) { + if (tmpDisplayedColumns[j].id == UserColumnFactory.NAME || tmpDisplayedColumns[j].id == UserColumnFactory.LINEUP || tmpDisplayedColumns[j].id == UserColumnFactory.BEST_POSITION || tmpDisplayedColumns[j].id == UserColumnFactory.SCHUM_RANK_BENCHMARK || tmpDisplayedColumns[j].id == UserColumnFactory.GROUP) { + m_clData!![i][j] = (tmpDisplayedColumns[j] as PlayerColumn).getTableEntry(currentPlayer, null) + } else if (tmpDisplayedColumns[j].id == UserColumnFactory.AUTO_LINEUP) { + m_clData!![i][j] = (tmpDisplayedColumns[j] as BooleanColumn).getValue(currentPlayer) + } + } } } + + companion object { + @Serial + private const val serialVersionUID = 5149408240369536138L + } } diff --git a/src/main/java/core/model/HOConfigurationIntParameter.kt b/src/main/java/core/model/HOConfigurationIntParameter.kt index 3dd80a0b5..dae6bb5d6 100644 --- a/src/main/java/core/model/HOConfigurationIntParameter.kt +++ b/src/main/java/core/model/HOConfigurationIntParameter.kt @@ -1,30 +1,30 @@ -package core.model; +package core.model /** * Configuration parameter of integer type */ -public class HOConfigurationIntParameter extends HOConfigurationParameter { +class HOConfigurationIntParameter(key: String, defaultValue: Int) : + HOConfigurationParameter(key, defaultValue.toString()) { /** * Parameter value as integer */ - private int intValue; + private var intValue: Int /** * Constructor calls string constructor * @param key Parameter key * @param defaultValue Default integer value */ - public HOConfigurationIntParameter(String key, int defaultValue) { - super(key, String.valueOf(defaultValue)); - this.intValue = parameters.getInt(key, defaultValue); + init { + this.intValue = parameters.getInt(key, defaultValue) } /** * Return the parameter integer value * @return int */ - public int getIntValue() { - return this.intValue; + fun getIntValue(): Int { + return this.intValue } /** @@ -32,10 +32,10 @@ public class HOConfigurationIntParameter extends HOConfigurationParameter { * ParameterChanged is set true if new value is different to previous parameter value * @param newValue New integer value */ - public void setIntValue(int newValue) { + fun setIntValue(newValue: Int) { if (this.intValue != newValue) { - this.intValue = newValue; - setValue(String.valueOf(newValue)); + this.intValue = newValue + setValue(newValue.toString()) } } } \ No newline at end of file diff --git a/src/main/java/core/model/HOConfigurationParameter.kt b/src/main/java/core/model/HOConfigurationParameter.kt index 8ef3dace5..4f5045bc8 100644 --- a/src/main/java/core/model/HOConfigurationParameter.kt +++ b/src/main/java/core/model/HOConfigurationParameter.kt @@ -1,36 +1,28 @@ -package core.model; +package core.model -import core.db.AbstractTable; -import core.db.DBManager; - -import java.util.Objects; +import core.db.AbstractTable.Storable +import core.db.DBManager /** * Configuration parameters are registered in a static property register * which is saved in the user configuration table at application termination * Remark: This class should replace usage of UserParameter an HOParameter classes */ -public class HOConfigurationParameter extends AbstractTable.Storable { - - /** - * The parameters' registry - */ - static protected final HOProperties parameters = new HOProperties(); - +open class HOConfigurationParameter( /** - * Remember if parameters were changed + * Parameter key */ - static private boolean parametersChanged = false; - + val key: String, defaultValue: String? +) : Storable() { /** - * Parameter key + * Return the key + * @return String */ - private final String key; /** * Parameter value */ - private String value; + private var value: String? /** * Create configuration parameter @@ -39,32 +31,23 @@ public class HOConfigurationParameter extends AbstractTable.Storable { * @param key Parameter key * @param defaultValue Default value */ - public HOConfigurationParameter(String key, String defaultValue){ - this.key = key; - this.value = parameters.getProperty(key); - if (value == null){ - value = DBManager.instance().loadHOConfigurationParameter(key); + init { + this.value = parameters.getProperty(key) + if (value == null) { + value = DBManager.instance().loadHOConfigurationParameter(key) if (value == null) { - value = defaultValue; + value = defaultValue } - parameters.setProperty(key, value); + parameters.setProperty(key, value) } } - /** - * Return the key - * @return String - */ - public String getKey() { - return key; - } - /** * Return the value * @return String */ - public String getValue() { - return value; + fun getValue(): String? { + return value } /** @@ -72,21 +55,35 @@ public class HOConfigurationParameter extends AbstractTable.Storable { * ParameterChanged is the to true, if new value different to previous value * @param value New value */ - public void setValue(String value) { - if (!Objects.equals(value, this.value)){ - this.value = value; - parameters.setProperty(key, value); - parametersChanged = true; + fun setValue(value: String) { + if (value != this.value) { + this.value = value + parameters.setProperty(key, value) + parametersChanged = true } } - /** - * Store the current parameters of the registry in the database - */ - static public void storeParameters() { - if (parametersChanged){ - for (var p : parameters.entrySet()){ - DBManager.instance().saveUserParameter((String)p.getKey(), (String)p.getValue()); + companion object { + /** + * The parameters' registry + */ + @JvmStatic + protected val parameters: HOProperties = HOProperties() + + /** + * Remember if parameters were changed + */ + private var parametersChanged = false + + /** + * Store the current parameters of the registry in the database + */ + @JvmStatic + fun storeParameters() { + if (parametersChanged) { + for ((key, value) in parameters) { + DBManager.instance().saveUserParameter(key as String, value as String) + } } } } diff --git a/src/main/java/module/playerOverview/PlayerOverviewTable.kt b/src/main/java/module/playerOverview/PlayerOverviewTable.kt index 7a3df6e23..e7fc96cc1 100644 --- a/src/main/java/module/playerOverview/PlayerOverviewTable.kt +++ b/src/main/java/module/playerOverview/PlayerOverviewTable.kt @@ -1,130 +1,124 @@ -package module.playerOverview; - -import core.db.DBManager; -import core.gui.HOMainFrame; -import core.gui.RefreshManager; -import core.gui.comp.table.FixedColumnsTable; -import core.gui.comp.table.TableSorter; -import core.gui.model.PlayerOverviewTableModel; -import core.gui.model.UserColumnController; -import core.gui.model.UserColumnFactory; -import core.model.HOVerwaltung; -import core.model.TranslationFacility; -import core.model.match.MatchKurzInfo; -import core.model.player.Player; -import core.net.HattrickLink; -import javax.swing.*; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.Serial; +package module.playerOverview +import core.db.DBManager +import core.gui.HOMainFrame +import core.gui.RefreshManager +import core.gui.Refreshable +import core.gui.comp.table.FixedColumnsTable +import core.gui.model.PlayerOverviewTableModel +import core.gui.model.UserColumnController +import core.model.HOVerwaltung +import core.model.TranslationFacility +import core.model.player.Player +import core.net.HattrickLink +import java.awt.event.MouseAdapter +import java.awt.event.MouseEvent +import java.io.Serial /** * The Squad table, listing all the players on the team. * - *

The actual model for that table is defined in {@link PlayerOverviewTableModel}, which defines - * all the columns to be displayed; the columns are initiated by a factory, {@link UserColumnFactory}, - * which in particular sets their preferred width.

* - *

Sorting in the table is handled by {@link TableSorter} which decorates the model, and is set - * as the {@link javax.swing.table.TableModel} for this table. Triggering sorting by a click sorts + * The actual model for that table is defined in [PlayerOverviewTableModel], which defines + * all the columns to be displayed; the columns are initiated by a factory, [UserColumnFactory], + * which in particular sets their preferred width. + * + * + * Sorting in the table is handled by [TableSorter] which decorates the model, and is set + * as the [javax.swing.table.TableModel] for this table. Triggering sorting by a click sorts * the entries in the table model itself. The new sorting order is then used by re-displaying the * table. This approach differs from the “normal” Swing approach of using - * {@link JTable#setRowSorter(RowSorter)}.

- * + * [JTable.setRowSorter]. + * * @author Thorsten Dietz */ -public class PlayerOverviewTable extends FixedColumnsTable implements core.gui.Refreshable { - - @Serial - private static final long serialVersionUID = -6074136156090331418L; - private final PlayerOverviewTableModel tableModel; +class PlayerOverviewTable : FixedColumnsTable(UserColumnController.instance().playerOverviewModel), Refreshable { + val playerTableModel: PlayerOverviewTableModel = this.model as PlayerOverviewTableModel - public PlayerOverviewTable() { - super(UserColumnController.instance().getPlayerOverviewModel()); - tableModel = (PlayerOverviewTableModel)this.getModel(); - tableModel.setValues(HOVerwaltung.instance().getModel().getCurrentPlayers()); - tableModel.initTable(this); - setOpaque(false); - RefreshManager.instance().registerRefreshable(this); + init { + playerTableModel.setValues(HOVerwaltung.instance().model.currentPlayers) + playerTableModel.initTable(this) + isOpaque = false + RefreshManager.instance().registerRefreshable(this) - // Add a mouse listener that, when clicking on the “Last match” column - // - opens the Hattrick page for the player if you shift-click, - // - or opens the match in HO if you double-click. - addMouseListener(new MouseAdapter() { - @Override - public void mouseReleased(MouseEvent e) { - var player = getSelectedPlayer(); - if (player!=null) { - // Last match column - int columnAtPoint = columnAtPoint(e.getPoint()); - // Get name of the actual column at columnAtPoint, i.e. post-ordering of the columns - // based on preferences. - var columnName = tableModel.getColumnName(columnAtPoint); - String lastMatchRating = TranslationFacility.tr("LastMatchRating"); - if (columnName != null && columnName.equalsIgnoreCase(lastMatchRating)) { - if (e.isShiftDown()) { - int matchId = player.getLastMatchId(); - var matchType = player.getLastMatchType(); - MatchKurzInfo info = DBManager.instance().getMatchesKurzInfoByMatchID(matchId, matchType); - HattrickLink.showMatch(String.valueOf(matchId), info.getMatchType().isOfficial()); - } else if (e.getClickCount() == 2) { - HOMainFrame.instance().showMatch(player.getLastMatchId()); - } - } - } - } - }); - } + // Add a mouse listener that, when clicking on the “Last match” column + // - opens the Hattrick page for the player if you shift-click, + // - or opens the match in HO if you double-click. + addMouseListener(object : MouseAdapter() { + override fun mouseReleased(e: MouseEvent) { + val player: Player? = selectedPlayer + if (player != null) { + // Last match column + val columnAtPoint = columnAtPoint(e.point) + // Get name of the actual column at columnAtPoint, i.e. post-ordering of the columns + // based on preferences. + val columnName = playerTableModel.getColumnName(columnAtPoint) + val lastMatchRating = TranslationFacility.tr("LastMatchRating") + if (columnName != null && columnName.equals(lastMatchRating, ignoreCase = true)) { + if (e.isShiftDown) { + val matchId = player.lastMatchId + val matchType = player.lastMatchType + val info = DBManager.instance().getMatchesKurzInfoByMatchID(matchId, matchType) + HattrickLink.showMatch(matchId.toString(), info.matchType.isOfficial) + } else if (e.clickCount == 2) { + HOMainFrame.instance().showMatch(player.lastMatchId) + } + } + } + } + }) + } - public Player getSelectedPlayer(){ - var rowIndex = getSelectedRow(); - if (rowIndex >= 0) { - return tableModel.getPlayers().get(convertRowIndexToModel(rowIndex)); - } - return null; - } + val selectedPlayer: Player? + get() { + val rowIndex = selectedRow + if (rowIndex >= 0) { + return playerTableModel.players!![convertRowIndexToModel(rowIndex)] + } + return null + } - public final void selectPlayer(int playerId) { - var index = tableModel.getPlayerIndex(playerId); - if (index >= 0) { - index = convertRowIndexToView(index); - this.setRowSelectionInterval(index, index); - } - } + fun selectPlayer(playerId: Int) { + var index = playerTableModel.getPlayerIndex(playerId) + if (index >= 0) { + index = convertRowIndexToView(index) + this.setRowSelectionInterval(index, index) + } + } - @Override - public final void reInit() { - var player = getSelectedPlayer(); - resetPlayers(); - repaint(); - if ( player != null ) {selectPlayer(player.getPlayerId());} - } + override fun reInit() { + val player = selectedPlayer + resetPlayers() + repaint() + if (player != null) { + selectPlayer(player.playerId) + } + } - public final void reInitModel() { - tableModel.reInitData(); - } + fun reInitModel() { + playerTableModel.reInitData() + } - public final void reInitModelHRFComparison() { - tableModel.reInitDataHRFComparison(); - } + fun reInitModelHRFComparison() { + playerTableModel.reInitDataHRFComparison() + } - @Override - public final void refresh() { - reInitModel(); - repaint(); - } + override fun refresh() { + reInitModel() + repaint() + } - public final void refreshHRFComparison() { - reInitModelHRFComparison(); - repaint(); - } + fun refreshHRFComparison() { + reInitModelHRFComparison() + repaint() + } - private void resetPlayers() { - tableModel.setValues(HOVerwaltung.instance().getModel().getCurrentPlayers()); - } + private fun resetPlayers() { + playerTableModel.setValues(HOVerwaltung.instance().model.currentPlayers) + } - public PlayerOverviewTableModel getPlayerTableModel(){ - return tableModel; - } + companion object { + @Serial + private val serialVersionUID = -6074136156090331418L + } } diff --git a/src/main/resources/release_notes.md b/src/main/resources/release_notes.md index 9c8cc4a74..371fe4cf1 100644 --- a/src/main/resources/release_notes.md +++ b/src/main/resources/release_notes.md @@ -8,8 +8,7 @@ ### Database * Increase match report column size (#2065) -* Table `STADION`: Added column `REBUILT_DATE` and - `EXPANSION_DATE` ([#2140](https://github.com/ho-dev/HattrickOrganizer/issues/2140)) +* Table `STADION`: Added column `REBUILT_DATE` and `EXPANSION_DATE` (#2140) ### Squad @@ -18,7 +17,7 @@ ### Team Analyzer * Fix illegal argument exception in team rating panel (#2155) -* + ### Player Analysis * Fix error in rating compare table (#2153) @@ -46,10 +45,9 @@ ### Misc -* Arena sizer: Added the Arena Info Panel (feature [#2140](https://github.com/ho-dev/HattrickOrganizer/issues/2140)) in - the tab with name of the stadium. -* Fix #2137: Resolved an issue where the Download Dialog would not reappear after being closed with the 'X' button. The - dialog will now correctly reappear when triggered again. +* Arena sizer: Added the Arena Info Panel in the tab with name of the stadium. (#2140) +* Resolved an issue where the Download Dialog would not reappear after being closed with the 'X' button. The + dialog will now correctly reappear when triggered again. (#2137) ## Translations From 2663987164d50a80865414769bf070db70df6842 Mon Sep 17 00:00:00 2001 From: wsbrenk Date: Mon, 4 Nov 2024 19:46:28 +0100 Subject: [PATCH 3/3] Porting HOTableModel and others to Kotlin --- src/main/java/core/gui/comp/table/HOTableModel.kt | 10 +++++----- .../java/core/model/HOConfigurationIntParameter.kt | 2 -- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/core/gui/comp/table/HOTableModel.kt b/src/main/java/core/gui/comp/table/HOTableModel.kt index 56eac9c2c..e058fe54c 100644 --- a/src/main/java/core/gui/comp/table/HOTableModel.kt +++ b/src/main/java/core/gui/comp/table/HOTableModel.kt @@ -75,7 +75,7 @@ abstract class HOTableModel protected constructor( get() { val columnNames = arrayOfNulls(displayedColumnCount) - for (i in getDisplayedColumns().indices) columnNames[i] = getDisplayedColumns()[i]!!.getColumnName() + for (i in getDisplayedColumns().indices) columnNames[i] = getDisplayedColumns()[i].getColumnName() return columnNames } @@ -87,7 +87,7 @@ abstract class HOTableModel protected constructor( */ get() { val tooltips = arrayOfNulls(displayedColumnCount) - for (i in getDisplayedColumns().indices) tooltips[i] = getDisplayedColumns()[i]!!.getTooltip() + for (i in getDisplayedColumns().indices) tooltips[i] = getDisplayedColumns()[i].getTooltip() return tooltips } @@ -177,7 +177,7 @@ abstract class HOTableModel protected constructor( */ override fun getColumnName(columnIndex: Int): String? { if (displayedColumnCount > columnIndex) { - return getDisplayedColumns()[columnIndex]!!.getColumnName() + return getDisplayedColumns()[columnIndex].getColumnName() } return null @@ -205,7 +205,7 @@ abstract class HOTableModel protected constructor( fun getPositionInArray(searchid: Int): Int { val tmpColumns = getDisplayedColumns() for (i in tmpColumns.indices) { - if (tmpColumns[i]!!.getId() == searchid) return i + if (tmpColumns[i].getId() == searchid) return i } return -1 } @@ -310,7 +310,7 @@ abstract class HOTableModel protected constructor( for (i in 0 until displayedColumnsCount) { val userColumn = displayedColumns[i] val tableColumn = getTableColumn(table, i) - tableColumn.identifier = userColumn!!.getId() + tableColumn.identifier = userColumn.getId() } getUserColumnSettings(table) val rowSorter = TableRowSorter(this) diff --git a/src/main/java/core/model/HOConfigurationIntParameter.kt b/src/main/java/core/model/HOConfigurationIntParameter.kt index dae6bb5d6..dc1a5d18a 100644 --- a/src/main/java/core/model/HOConfigurationIntParameter.kt +++ b/src/main/java/core/model/HOConfigurationIntParameter.kt @@ -12,8 +12,6 @@ class HOConfigurationIntParameter(key: String, defaultValue: Int) : /** * Constructor calls string constructor - * @param key Parameter key - * @param defaultValue Default integer value */ init { this.intValue = parameters.getInt(key, defaultValue)