001package ball.swing.table;
002/*-
003 * ##########################################################################
004 * Utilities
005 * %%
006 * Copyright (C) 2008 - 2022 Allen D. Ball
007 * %%
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *      http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 * ##########################################################################
020 */
021import java.util.Map;
022import javax.swing.event.TableModelEvent;
023import lombok.ToString;
024
025/**
026 * {@link Map} {@link javax.swing.table.TableModel} implementation.
027 *
028 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
029 */
030@ToString
031public class MapTableModel extends ArrayListTableModel<Object> {
032    private static final long serialVersionUID = -8225255612163673800L;
033
034    /** @serial */ private final Map<?,?> map;
035
036    /**
037     * @see AbstractTableModelImpl#AbstractTableModelImpl(String...)
038     *
039     * @param   map             The underlying {@link Map}.
040     * @param   names           The column names.
041     */
042    public MapTableModel(Map<?,?> map, String... names) {
043        super(map.keySet(), names);
044
045        this.map = map;
046    }
047
048    /**
049     * @see AbstractTableModelImpl#AbstractTableModelImpl(int)
050     *
051     * @param   map             The underlying {@link Map}.
052     * @param   columns         The number of columns.
053     */
054    public MapTableModel(Map<?,?> map, int columns) {
055        this(map, new String[columns]);
056    }
057
058    /**
059     * @param   map             The underlying {@link Map}.
060     */
061    public MapTableModel(Map<?,?> map) { this(map, 2); }
062
063    /**
064     * Method to get the underlying {@link Map}.
065     *
066     * @return  The underlying {@link Map}.
067     */
068    protected Map<?,?> map() { return map; }
069
070    @Override
071    protected Object getValueAt(Object row, int x) {
072        Object value = null;
073
074        switch (x) {
075        case 0:
076            value = row;
077            break;
078
079        default:
080            value = map().get(row);
081            break;
082        }
083
084        return value;
085    }
086
087    @Override
088    public void tableChanged(TableModelEvent event) {
089        list().clear();
090        list().addAll(map().keySet());
091
092        super.tableChanged(event);
093    }
094}