All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.uvm.ccts.common.util.TableUtil Maven / Gradle / Ivy

Go to download

A library of useful generic objects and tools consolidated here to simplify all UVM CCTS projects

There is a newer version: 1.1.5
Show newest version
/*
 * Copyright 2015 The University of Vermont and State
 * Agricultural College.  All rights reserved.
 *
 * Written by Matthew B. Storer 
 *
 * This file is part of CCTS Common.
 *
 * CCTS Common is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CCTS Common 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 Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with CCTS Common.  If not, see .
 */

package edu.uvm.ccts.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.*;

/**
 * Created by mstorer on 2/5/14.
 */
public class TableUtil {
    private static final Log log = LogFactory.getLog(TableUtil.class);

    private static final int DEFAULT_MARGIN_WIDTH = 10;
    private static final int DEFAULT_MAX_WIDTH = 200;


    public static void adjustColumnWidths(JTable table) {
        adjustColumnWidths(table, null, null, null, null);
    }

    public static void adjustColumnWidth(JTable table, int column) {
        adjustColumnWidths(table, column, column, null, null);
    }

    public static void adjustColumnWidths(JTable table, Integer marginWidth, Integer maxWidth) {
        adjustColumnWidths(table, null, null, marginWidth, maxWidth);
    }

    public static void adjustColumnWidths(JTable table,
                                          Integer firstCol, Integer lastCol,
                                          Integer marginWidth, Integer maxWidth) {

        if (firstCol == null)       firstCol = 0;
        if (lastCol == null)        lastCol = table.getColumnCount() - 1;
        if (marginWidth == null)    marginWidth = DEFAULT_MARGIN_WIDTH;
        if (maxWidth == null)       maxWidth = DEFAULT_MAX_WIDTH;

        JTableHeader header = table.getTableHeader();
        FontMetrics metrics = header.getFontMetrics(header.getFont());
        for (int c = firstCol; c <= lastCol; c ++) {
            int hw = metrics.stringWidth(table.getColumnName(c));

            int w = 0;
            for (int r = 0; r < table.getRowCount(); r ++) {
                TableCellRenderer renderer = table.getCellRenderer(r, c);
                Component comp = table.prepareRenderer(renderer, r, c);
                w = Math.max(comp.getPreferredSize().width, w);
            }

            w = Math.min(w, maxWidth);
            w = Math.max(w, hw);

            table.getColumnModel().getColumn(c).setPreferredWidth(w + marginWidth);
        }
    }

    public static void makeAutoResizable(final JTable table) {
        makeAutoResizable(table, null, null);
    }

    public static void makeAutoResizable(final JTable table, final Integer marginWidth, final Integer maxColWidth) {
        if (table.getParent() instanceof JViewport) {
            JViewport viewPort = (JViewport) table.getParent();
            viewPort.addComponentListener(new ComponentAdapter() {
                @Override
                public void componentResized(ComponentEvent e) {
                    JViewport viewPort = (JViewport) table.getParent();

                    int calculatedWidth = calculateWidth(table, marginWidth, maxColWidth);

//                    log.info("viewPort width = " + viewPort.getWidth() + ", table width = " + table.getWidth() + ", calculatedWidth = " + calculatedWidth);

                    if (viewPort.getWidth() > calculatedWidth) table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                    else                                       table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                }
            });
        }
    }

    public static void addContextMenu(final JTable table) {
        final JPopupMenu ctxMenu = new JPopupMenu();

        JMenuItem ctxmiDefaultSort = new JMenuItem();
        ctxmiDefaultSort.setText("Default Sorting");
        ctxmiDefaultSort.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                table.getRowSorter().setSortKeys(null);
            }
        });
        ctxMenu.add(ctxmiDefaultSort);

        JMenuItem ctxmiDefaultWidths = new JMenuItem();
        ctxmiDefaultWidths.setText("Default Column Widths");
        ctxmiDefaultWidths.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                adjustColumnWidths(table);
            }
        });
        ctxMenu.add(ctxmiDefaultWidths);

//        log.info("adding table context menu");

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    ctxMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
    }

    private static int calculateWidth(JTable table, Integer marginWidth, Integer maxColWidth) {
        if (marginWidth == null) marginWidth = DEFAULT_MARGIN_WIDTH;
        if (maxColWidth == null) maxColWidth = DEFAULT_MAX_WIDTH;

        int calculatedWidth = 3;

        // todo : this duplicates a lot of code from adjustColumnWidths.  not very DRY.  make DRY.

        JTableHeader header = table.getTableHeader();
        FontMetrics metrics = header.getFontMetrics(header.getFont());
        for (int c = 0; c < table.getColumnCount(); c ++) {
            int hw = metrics.stringWidth(table.getColumnName(c));

            int w = 0;
            for (int r = 0; r < table.getRowCount(); r ++) {
                TableCellRenderer renderer = table.getCellRenderer(r, c);
                Component comp = table.prepareRenderer(renderer, r, c);
                w = Math.max(comp.getPreferredSize().width, w);
            }

            w = Math.min(w, maxColWidth);
            w = Math.max(w, hw);

            calculatedWidth += (w + marginWidth);
        }

        return calculatedWidth;
    }

    public static void adjustColumnWidthsToFitHeaders(JTable table) {
        adjustColumnWidthsToFitHeaders(table, null);
    }

    public static void adjustColumnWidthsToFitHeaders(JTable table, Integer marginWidth) {
        if (marginWidth == null) marginWidth = DEFAULT_MARGIN_WIDTH;

        JTableHeader header = table.getTableHeader();
        FontMetrics metrics = header.getFontMetrics(header.getFont());
        for (int i = 0; i < table.getColumnCount(); i ++) {
            int w = metrics.stringWidth(table.getColumnName(i)) + marginWidth;
            table.getColumnModel().getColumn(i).setPreferredWidth(w);
        }
    }

    public static void adjustColumnWidthsToFitData(JTable table) {
        adjustColumnWidthsToFitData(table, null);
    }

    public static void adjustColumnWidthsToFitData(JTable table, Integer marginWidth) {
        if (marginWidth == null) marginWidth = DEFAULT_MARGIN_WIDTH;

        for (int c = 0; c < table.getColumnCount(); c ++) {
            int w = 0;
            for (int r = 0; r < table.getRowCount(); r ++) {
                TableCellRenderer renderer = table.getCellRenderer(r, c);
                Component comp = table.prepareRenderer(renderer, r, c);
                w = Math.max(comp.getPreferredSize().width, w);
            }
            table.getColumnModel().getColumn(c).setPreferredWidth(w + marginWidth);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy