net.kamhon.ieagle.swing.table.KTable.java Source code

Java tutorial

Introduction

Here is the source code for net.kamhon.ieagle.swing.table.KTable.java

Source

/*
 * Copyright 2012 Eng Kam Hon (kamhon@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.kamhon.ieagle.swing.table;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import net.kamhon.ieagle.swing.KTextField;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.swingx.JXTable;

public class KTable<T> extends JXTable {
    private static final long serialVersionUID = 1L;

    protected KTableModel<T> tableModel;
    private static final Log log = LogFactory.getLog(KTable.class);

    public KTable(KTableColumn[] columns) {
        super();
        List<KTableColumn> array = new ArrayList<KTableColumn>();
        for (KTableColumn column : columns) {
            array.add(column);
        }

        initComponents(array);
    }

    public KTable(List<KTableColumn> columns) {
        super();
        initComponents(columns);
        // tableModel.setColumns(columns);
    }

    private void initComponents(List<KTableColumn> columns) {
        tableModel = new KTableModel<T>(this, columns);
        setModel(tableModel);

        // final KTable<T> table = this;

        for (int i = 0; i < columns.size(); i++) {
            KTableColumn column = columns.get(i);
            TableColumn tc = columnModel.getColumn(i);
            tc.setHeaderValue(column.getColumnLabel());

            if (column instanceof KTableCheckBoxColumn) {
                BooleanEditor cellEditor = new BooleanEditor();

                if (column instanceof KTableRowCheckBoxColumn) {
                    /*final JCheckBox component = (JCheckBox) cellEditor.getComponent();
                    component.addActionListener(new ActionListener() {
                       @Override
                       public void actionPerformed(ActionEvent e) {
                      int[] selectedRows = table.getSelectedRows();
                      int selectedRow = table.getSelectedRow();
                          
                      log.debug("selectedRows = " + selectedRows);
                      log.debug("selectedRow = " + selectedRow);
                      if (component.isSelected()) {
                        
                      }
                       }
                    });*/
                    // log.debug("component = " + component);
                }

                tc.setCellEditor(cellEditor);
                tc.setCellRenderer(this.getDefaultRenderer(Boolean.class));
                tc.setHeaderRenderer(new KTableHeaderCheckBox(this));
            } else if (column instanceof KTableTextColumn) {
                KTextField textField = new KTextField();
                textField.setEditable(false);

                tc.setCellEditor(new GenericEditor(textField));
            }
        }

        setColumnControlVisible(true);
        setShowGrid(false, false);
    }

    public void setData(List<T> datas) {
        tableModel.setData(datas);
    }

    @Override
    public int getSelectedRow() {
        if (tableModel.isHasRowCheckBox()) {
            int[] selectedRows = getSelectedRows();
            if (selectedRows.length == 0) {
                return -1;
            } else {
                return selectedRows[0];
            }
        } else {
            return super.getSelectedRow();
        }
    }

    @Override
    public int[] getSelectedRows() {
        if (tableModel.isHasRowCheckBox()) {
            int noOfRow = tableModel.getRowCount();

            int columnIndex = -1;
            List<KTableColumn> columns = tableModel.getColumns();
            for (int i = 0; i < columns.size(); i++) {
                KTableColumn column = columns.get(i);
                if (column instanceof KTableRowCheckBoxColumn) {
                    columnIndex = i;
                    break;
                }
            }

            List<Integer> checkedRows = new ArrayList<Integer>();
            for (int r = 0; r < noOfRow; r++) {
                int rowModel = convertRowIndexToModel(r);
                log.debug("rowModel = " + rowModel);
                Boolean checked = (Boolean) tableModel.getValueAt(rowModel, columnIndex);
                if (checked) {
                    checkedRows.add(r);
                }
            }

            int[] array = new int[checkedRows.size()];
            for (int i = 0; i < checkedRows.size(); i++) {
                array[i] = checkedRows.get(i);
            }

            log.debug("===================");

            return array;
        } else {
            return super.getSelectedRows();
        }
    }

    @Override
    public int getSelectedRowCount() {
        if (tableModel.isHasRowCheckBox()) {
            return getSelectedRows().length;
        } else {
            return super.getSelectedRowCount();
        }
    }

    public T getRecord(int rowIndex) {
        int rowModel = convertRowIndexToModel(rowIndex);
        log.debug("rowModel = " + rowModel);
        return tableModel.getRecord(convertRowIndexToModel(rowModel));
    }

    /*********************************************************
     * INNER CLASS - START
     *********************************************************/
    private class KTableHeaderCheckBox extends JCheckBox implements TableCellRenderer, MouseListener {
        private static final long serialVersionUID = 1L;

        private JTable table;
        private String headerLabel;

        private KTableHeaderCheckBox rendererComponent;
        private int column;
        private boolean mousePressed = false;

        public KTableHeaderCheckBox(JTable table) {
            this(table, null);
        }

        public KTableHeaderCheckBox(JTable table, String headerLabel) {
            rendererComponent = this;
            this.table = table;
            this.headerLabel = headerLabel;
            rendererComponent.addItemListener(new MyItemListener());
        }

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            if (table != null) {
                JTableHeader header = table.getTableHeader();
                if (header != null) {
                    rendererComponent.setHorizontalAlignment(CENTER);
                    rendererComponent.setForeground(header.getForeground());
                    rendererComponent.setBackground(header.getBackground());
                    rendererComponent.setFont(header.getFont());
                    header.addMouseListener(rendererComponent);
                }
            }
            setColumn(column);
            if (StringUtils.isNotBlank(headerLabel))
                rendererComponent.setText(headerLabel);
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            return rendererComponent;
        }

        protected void setColumn(int column) {
            this.column = column;
        }

        protected void handleClickEvent(MouseEvent e) {
            if (mousePressed) {
                mousePressed = false;
                JTableHeader header = (JTableHeader) (e.getSource());
                JTable tableView = header.getTable();
                TableColumnModel columnModel = tableView.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = tableView.convertColumnIndexToModel(viewColumn);

                if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
                    doClick();
                }
            }
        }

        public void mouseClicked(MouseEvent e) {
            handleClickEvent(e);
            ((JTableHeader) e.getSource()).repaint();
        }

        public void mousePressed(MouseEvent e) {
            mousePressed = true;
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        private class MyItemListener implements ItemListener {
            public void itemStateChanged(ItemEvent e) {
                Object source = e.getSource();
                if (source instanceof AbstractButton == false)
                    return;
                boolean checked = e.getStateChange() == ItemEvent.SELECTED;

                for (int x = 0; x < table.getModel().getColumnCount(); x++) {
                    TableCellRenderer cellRenderer = table.getColumnModel().getColumn(x).getHeaderRenderer();
                    if (cellRenderer == source) {
                        for (int y = 0; y < table.getRowCount(); y++) {
                            table.setValueAt(checked, y, x);
                        }
                        break;
                    }
                }
            }
        }
    }

    /*********************************************************
     * INNER CLASS - END
     *********************************************************/
}