Example usage for javax.swing JTable getTableHeader

List of usage examples for javax.swing JTable getTableHeader

Introduction

In this page you can find the example usage for javax.swing JTable getTableHeader.

Prototype

public JTableHeader getTableHeader() 

Source Link

Document

Returns the tableHeader used by this JTable.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.ESResultsTablePanel.java

/**
 * @param table/*  w w  w.ja va  2s .co m*/
 * @param model
 */
protected void autoResizeColWidth(final JTable table, final DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();

    int preferredWidthTotal = 0;
    int renderedWidthTotal = 0;
    int[] colWidths = new int[table.getColumnCount()];
    int[] strWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        TableCellRenderer headerRenderer = col.getHeaderRenderer();
        if (headerRenderer instanceof JLabel) {
            ((JLabel) headerRenderer).setHorizontalAlignment(SwingConstants.CENTER);
        }

        // Get width of column header
        TableCellRenderer renderer = col.getCellRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0,
                0);

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        int strWidth = 0;
        boolean isString = model.getColumnClass(i) == String.class;
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            Object objVal = table.getValueAt(r, vColIndex);
            if (isString && objVal != null) {
                strWidth = Math.max(strWidth, ((String) objVal).length());
            }
            comp = renderer.getTableCellRendererComponent(table, objVal, false, false, r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        preferredWidthTotal += col.getPreferredWidth();
        colWidths[i] = width;
        strWidths[i] = strWidth;

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            TableColumn col = colModel.getColumn(i);
            TableCellRenderer renderer = col.getCellRenderer();
            if (renderer != null) {
                ((JLabel) renderer).setHorizontalAlignment(
                        strWidths[i] > 20 ? SwingConstants.LEFT : SwingConstants.CENTER);
                //((JLabel)renderer).setHorizontalAlignment(SwingConstants.LEFT);
            }

            if (model.getColumnCount() > 3 && renderedWidthTotal > preferredWidthTotal) {
                col.setPreferredWidth(colWidths[i]);
            }
        }
    }

    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    table.getTableHeader().setReorderingAllowed(false);
}

From source file:com.net2plan.gui.utils.onlineSimulationPane.OnlineSimulationPane.java

/**
 * Shows the future event list.//w w  w .j  a  v a2s .co m
 *
 * @since 0.3.0
 */
public void viewFutureEventList() {
    final JDialog dialog = new JDialog();
    dialog.setTitle("Future event list");
    SwingUtils.configureCloseDialogOnEscape(dialog);
    dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
    dialog.setSize(new Dimension(500, 300));
    dialog.setLocationRelativeTo(null);
    dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    dialog.setLayout(new MigLayout("fill, insets 0 0 0 0"));

    final String[] tableHeader = StringUtils.arrayOf("Id", "Time", "Priority", "Type", "To module",
            "Custom object");
    Object[][] data = new Object[1][tableHeader.length];

    DefaultTableModel model = new ClassAwareTableModel();
    model.setDataVector(new Object[1][tableHeader.length], tableHeader);

    JTable table = new AdvancedJTable(model);
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);
    JScrollPane scrollPane = new JScrollPane(table);
    dialog.add(scrollPane, "grow");

    PriorityQueue<SimEvent> futureEventList = simKernel.getSimCore().getFutureEventList().getPendingEvents();
    if (!futureEventList.isEmpty()) {
        int numEvents = futureEventList.size();
        SimEvent[] futureEventList_array = futureEventList.toArray(new SimEvent[numEvents]);
        Arrays.sort(futureEventList_array, futureEventList.comparator());
        data = new Object[numEvents][tableHeader.length];

        for (int eventId = 0; eventId < numEvents; eventId++) {
            //            List<SimAction> actions = futureEventList_array[eventId].getEventActionList();
            Object customObject = futureEventList_array[eventId].getEventObject();
            data[eventId][0] = eventId;
            data[eventId][1] = StringUtils
                    .secondsToYearsDaysHoursMinutesSeconds(futureEventList_array[eventId].getEventTime());
            data[eventId][2] = futureEventList_array[eventId].getEventPriority();
            data[eventId][3] = futureEventList_array[eventId].getEventType();
            data[eventId][4] = futureEventList_array[eventId].getEventDestinationModule().toString();
            data[eventId][5] = customObject == null ? "none" : customObject;
        }
    }

    model.setDataVector(data, tableHeader);
    table.getTableHeader().addMouseListener(new ColumnFitAdapter());
    table.setDefaultRenderer(Double.class, new CellRenderers.NumberCellRenderer());

    dialog.setVisible(true);
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Sets a JTable to have the headers be centered. Also, the caller can indicate whether
 * and "String" columns are also centered.
 * @param table the table//from  w w  w  .  j a v  a  2s  . com
 * @param dataColsAlso whether the String data columns should be cetnered.
 */
public static void makeTableHeadersCentered(final JTable table, final boolean dataColsAlso) {
    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.CENTER);

    if (dataColsAlso) {
        TableCellRenderer tcr = table.getDefaultRenderer(String.class);

        // For Strings with no changes made to the table, the render is a DefaultTableCellRender.
        DefaultTableCellRenderer dtcr = (DefaultTableCellRenderer) tcr;

        // set the alignment to center
        dtcr.setHorizontalAlignment(SwingConstants.CENTER);
    }
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Calculates and sets the each column to it preferred size.  NOTE: This
 * method also sets the table height to 10 rows.
 * //from  ww w . j av  a2  s  .c  o  m
 * @param table the table to fix up
 * @param numRowsHeight the number of rows to make the table height (or null not to set it)
 */
public static void calcColumnWidths(final JTable table, final Integer numRowsHeight, final Integer maxWidth) {
    if (table != null) {
        JTableHeader header = table.getTableHeader();

        TableCellRenderer defaultHeaderRenderer = null;

        if (header != null) {
            defaultHeaderRenderer = header.getDefaultRenderer();
        }

        TableColumnModel columns = table.getColumnModel();
        TableModel data = table.getModel();

        int margin = columns.getColumnMargin(); // only JDK1.3

        int rowCount = data.getRowCount();

        int totalWidth = 0;

        for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
            TableColumn column = columns.getColumn(i);

            int columnIndex = column.getModelIndex();

            int width = -1;

            TableCellRenderer h = column.getHeaderRenderer();

            if (h == null)
                h = defaultHeaderRenderer;

            if (h != null) // Not explicitly impossible
            {
                Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1,
                        i);

                width = c.getPreferredSize().width;
            }

            for (int row = rowCount - 1; row >= 0; --row) {
                TableCellRenderer r = table.getCellRenderer(row, i);

                Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false,
                        false, row, i);

                width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer

                if (maxWidth != null) {
                    width = Math.min(width, maxWidth);
                }
            }

            if (width >= 0) {
                column.setPreferredWidth(width + margin); // <1.3: without margin
            } else {
                // ???
            }

            totalWidth += column.getPreferredWidth();
        }

        // If you like; This does not make sense for two many columns!
        Dimension size = table.getPreferredScrollableViewportSize();
        //if (totalWidth > size.width)
        {
            if (numRowsHeight != null) {
                size.height = Math.min(size.height, table.getRowHeight() * numRowsHeight);
            }
            size.width = totalWidth;
            table.setPreferredScrollableViewportSize(size);
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.java

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 *//*from ww  w  .  ja  v a2s .  c o m*/
private void initColumnSizes(final JTable tableArg) {
    ColTableModel tblModel = (ColTableModel) tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    TableCellRenderer headerRenderer = tableArg.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < tblModel.getColumnCount(); i++) {
        column = tableArg.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        /*
        if (DEBUG) {
        System.out.println("Initializing width of column "
                           + i + ". "
                           + "headerWidth = " + headerWidth
                           + "; cellWidth = " + cellWidth);
        }*/

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * @param table/*  ww  w  .  j a  va  2s .c  o m*/
 * @param model
 * @return
 */
public static JTable autoResizeColWidth(final JTable table, final DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();

    int preferredWidthTotal = 0;
    int renderedWidthTotal = 0;
    int[] colWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();

        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0,
                0);

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                    r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        preferredWidthTotal += col.getPreferredWidth();
        colWidths[i] = width;

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            colModel.getColumn(i).setPreferredWidth(colWidths[i]);
        }
    }

    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    table.getTableHeader().setReorderingAllowed(false);

    return table;
}

From source file:com.googlecode.vfsjfilechooser2.filepane.VFSFilePane.java

public JPanel createDetailsView() {
    final VFSJFileChooser chooser = getFileChooser();

    JPanel p = new JPanel(new BorderLayout());

    final JTable detailsTable = new JTable(getDetailsTableModel()) {
        // Handle Escape key events here
        @Override/*w w  w  .  j a va 2 s.c  o  m*/
        protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
            if ((e.getKeyCode() == KeyEvent.VK_ESCAPE) && (getCellEditor() == null)) {
                // We are not editing, forward to filechooser.
                chooser.dispatchEvent(e);

                return true;
            }

            return super.processKeyBinding(ks, e, condition, pressed);
        }

        @Override
        public void tableChanged(TableModelEvent e) {
            super.tableChanged(e);

            if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                // update header with possibly changed column set
                updateDetailsColumnModel(this);
            }
        }
    };

    //        detailsTable.setRowSorter(getRowSorter());
    detailsTable.setAutoCreateColumnsFromModel(false);
    detailsTable.setComponentOrientation(chooser.getComponentOrientation());
    //detailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    detailsTable.setShowGrid(false);
    detailsTable.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);

    //        detailsTable.addKeyListener(detailsKeyListener);
    Font font = list.getFont();
    detailsTable.setFont(font);
    detailsTable.setIntercellSpacing(new Dimension(0, 0));

    TableCellRenderer headerRenderer = new AlignableTableHeaderRenderer(
            detailsTable.getTableHeader().getDefaultRenderer());
    detailsTable.getTableHeader().setDefaultRenderer(headerRenderer);

    TableCellRenderer cellRenderer = new DetailsTableCellRenderer(chooser);
    detailsTable.setDefaultRenderer(Object.class, cellRenderer);

    // So that drag can be started on a mouse press
    detailsTable.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    detailsTable.addMouseListener(getMouseHandler());
    // No need to addListSelectionListener because selections are forwarded
    // to our JList.

    // 4835633 : tell BasicTableUI that this is a file list
    detailsTable.putClientProperty("Table.isFileList", Boolean.TRUE);

    if (listViewWindowsStyle) {
        detailsTable.addFocusListener(repaintListener);
    }

    JTableHeader header = detailsTable.getTableHeader();
    header.setUpdateTableInRealTime(true);
    header.addMouseListener(detailsTableModel.new ColumnListener());
    header.setReorderingAllowed(true);

    // TAB/SHIFT-TAB should transfer focus and ENTER should select an item.
    // We don't want them to navigate within the table
    ActionMap am = SwingUtilities.getUIActionMap(detailsTable);
    am.remove("selectNextRowCell");
    am.remove("selectPreviousRowCell");
    am.remove("selectNextColumnCell");
    am.remove("selectPreviousColumnCell");
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);

    JScrollPane scrollpane = new JScrollPane(detailsTable);
    scrollpane.setComponentOrientation(chooser.getComponentOrientation());
    LookAndFeel.installColors(scrollpane.getViewport(), "Table.background", "Table.foreground");

    // Adjust width of first column so the table fills the viewport when
    // first displayed (temporary listener).
    scrollpane.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            JScrollPane sp = (JScrollPane) e.getComponent();
            fixNameColumnWidth(sp.getViewport().getSize().width);
            sp.removeComponentListener(this);
        }
    });

    // 4835633.
    // If the mouse is pressed in the area below the Details view table, the
    // event is not dispatched to the Table MouseListener but to the
    // scrollpane.  Listen for that here so we can clear the selection.
    scrollpane.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            JScrollPane jsp = ((JScrollPane) e.getComponent());
            JTable table = (JTable) jsp.getViewport().getView();

            if (!e.isShiftDown()
                    || (table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) {
                clearSelection();

                TableCellEditor tce = table.getCellEditor();

                if (tce != null) {
                    tce.stopCellEditing();
                }
            }
        }
    });

    detailsTable.setForeground(list.getForeground());
    detailsTable.setBackground(list.getBackground());

    if (listViewBorder != null) {
        scrollpane.setBorder(listViewBorder);
    }

    p.add(scrollpane, BorderLayout.CENTER);

    detailsTableModel.fireTableStructureChanged();

    return p;
}

From source file:semaforo.Semaforo.java

public synchronized void loadTableWeek(JTable TableWeek, int index) {
    Settings settings = Controller.getSettings();

    //TableWeek.getColumnModel().getColumn(0).setPreferredWidth(350); //150
    TableWeek.setRowHeight(20); //40
    //TableWeek.getColumnModel().getColumn(9).setPreferredWidth(350);//150
    TableWeek.setFont(new Font("Arial", Font.BOLD, 12));//18

    CustomRenderer cr = new CustomRenderer(TableWeek.getDefaultRenderer(Object.class), Color.LIGHT_GRAY,
            Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY);
    TableWeek.setDefaultRenderer(Object.class, cr);
    DefaultTableModel model = (DefaultTableModel) TableWeek.getModel();
    Object[] o = new Object[10];

    JTableHeader header = TableWeek.getTableHeader();
    header.setPreferredSize(new Dimension(10, 30)); //100
    TableWeek.getTableHeader().setFont(new Font("Arial", Font.BOLD, 15));

    /* DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
     centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
     TableWeek.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
     TableWeek.getColumnModel().getColumn(9).setCellRenderer(centerRenderer);
     TableWeek.setDefaultRenderer(String.class, centerRenderer);*/
    int num = settings.getTickers().size();

    /*   while(DDBB.loadData) {
     try {//from   w w w. ja v a 2s. c  om
     Thread.sleep(500);
     } catch (InterruptedException ex) {
     Logger.getLogger(Semaforo.class.getName()).log(Level.SEVERE, null, ex);
     }
     }*/
    if (TableWeek.getModel().getRowCount() > 0) {
        num = Math.min(settings.getTickers().size(), TableWeek.getModel().getRowCount());
    }

    for (int i = 0; i < num; i++) {
        o[0] = settings.getTickers().get(i).getMinValue(index);
        o[9] = settings.getTickers().get(i).getMaxValue(index);
        model.addRow(o);
    }
}

From source file:com.SE.myPlayer.MusicPlayerGUI.java

public void tableReferesh(JTable songData_Table, String tableName, String columName) {
        int emptyResultSet = 0;

        try {// www .  j ava 2 s .com
            con = db.getCon();
            stmt = con.createStatement();
            ResultSet rs;

            switch (tableName) {
            case "library":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            case "playlist":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            default:
                rs = stmt.executeQuery(
                        "Select library.id_songs, library.song_location, library.song_name, library.song_album, library.song_artist, library.genre, library.year, library.time, library.comment from playlist INNER JOIN library ON library.id_songs = playlist.id_songs AND playlist.playlist_name = '"
                                + tableName + "' order by " + columName + "");
                break;
            }

            DefaultTableModel myModel = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };

            String[] songsColumnsName = { "Location", "Name", "Album", "Artist", "Genre", "Year", "Time",
                    "Comment" };
            myModel.setColumnIdentifiers(songsColumnsName);

            ResultSetMetaData rsmd = rs.getMetaData();
            int colNumbers = rsmd.getColumnCount();

            Object[] objects = new Object[colNumbers];

            while (rs.next()) {
                emptyResultSet = 1;
                for (int i = 0; i < colNumbers - 1; i++) {
                    objects[i] = rs.getObject(i + 2);
                }
                myModel.addRow(objects);
            }

            if (emptyResultSet == 0) {
                myModel.addRow(objects);
            }

            songData_Table.setModel(myModel);

            rs = stmt.executeQuery("select col_name from col_name where col_status = 0");

            while (rs.next()) {
                songData_Table.removeColumn(songData_Table.getColumn(rs.getString(1)));
            }

            songData_Table.getTableHeader().removeMouseListener(ma);
            songData_Table.getTableHeader().addMouseListener(ma);
            songData_Table.setDragEnabled(true);
            songData_Table.setDropTarget(new DropTarget() {
                @Override
                public synchronized void drop(DropTargetDropEvent dtde) {

                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    Transferable t = dtde.getTransferable();

                    try {
                        if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.javaFileListFlavor);
                            String files = fileList.toString();
                            finalString = convertFileString(files);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        } else if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.stringFlavor);
                            String fileListString = fileList.toString();

                            fileListString = Arrays.toString(fileListString.split("\\n"));

                            String[] splitLocations = fileListString.split(",\\s");

                            for (int i = 0; i < splitLocations.length; i++) {
                                if (i == 0) {
                                    splitLocations[i] = splitLocations[i].substring(1,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                } else {
                                    splitLocations[i] = splitLocations[i].substring(0,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                }
                            }

                            for (int i = 0; i < splitLocations.length; i++) {
                                splitLocations[i] = sd.getLocations(splitLocations[i]);
                            }
                            finalString = Arrays.asList(splitLocations);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        }
                    } catch (UnsupportedFlavorException | IOException | InvalidDataException
                            | UnsupportedTagException ex) {
                        System.out.println("Error in second drop flavour............" + ex);
                    }
                }
            });

            if (con != null) {
                stmt.close();
                con.close();
            }
        } catch (SQLException e) {
            System.out.println("Error in Stmt " + e);
        }
    }

From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java

/**
 * Parses the given import file according to the users selection and creates/updates the Preview table,
 * showing the user how the import options effect the way the data will be imported into the spreadsheet.
 * @param table - the table to display the data
 * @return//from  www. j a va 2  s . co m
 * JTable - the table to display the data
 */
private JTable setCSVTableData(final JTable table) {
    try {
        log.debug("setTableData - file - " + configCSV.getFile().toString());
        CsvReader csv = new CsvReader(new FileInputStream(configCSV.getFile()), configCSV.getDelimiter(),
                configCSV.getCharset());
        csv.setEscapeMode(configCSV.getEscapeMode());
        csv.setTextQualifier(configCSV.getTextQualifier());

        String[] headers = {};
        Vector<String[]> tableDataVector = new Vector<String[]>();

        highestColumnCount = getLargestColumnCountFromCSV();

        if (configCSV.getFirstRowHasHeaders()) {
            csv.readHeaders();
            headers = csv.getHeaders();
        }

        int rowColumnCount = 0;
        while (csv.readRecord()) {
            //how many columns does this row of data contain
            rowColumnCount = csv.getColumnCount();
            //create an array that contains teh row data
            String[] rowData = new String[csv.getColumnCount()];
            for (int col = 0; col < csv.getColumnCount(); col++) {
                rowData[col] = csv.get(col);
            }
            //if the column count in this row of data is not as large
            //as the column header count, then "insert" blank string into the cells
            String[] newArray = padArray(highestColumnCount, rowData, false);
            //stick the row data into a vector because we do not know how many
            //rows of data there are
            tableDataVector.add(newArray);
        }

        if (!configCSV.getFirstRowHasHeaders() || headers == null) {
            //create headers with names Column1, Column2...
            headers = createDummyHeaders(rowColumnCount);
        }

        //if the header count is not as large as the longest column count in the data set
        //create dummy headers and append to end of table.
        headers = padArray(highestColumnCount, headers, true);

        log.debug("---------------------------------------------------");
        printArray(headers);
        log.debug("---------------------------------------------------");

        //pull row data out of vector and stick into an array for table model.
        String[][] tableData = new String[tableDataVector.size()][rowColumnCount];
        for (int i = 0; i < tableData.length; i++) {
            tableData[i] = tableDataVector.elementAt(i);
            printArray(tableData[i]);
        }

        if (checkForErrors(headers, tableData)) {
            errorPanel.showDataImportStatusPanel(true);
        } else {
            errorPanel.showDataImportStatusPanel(false);
        }

        if ((doesFirstRowHaveHeaders ? tableDataVector.size() - 1
                : tableDataVector.size()) > WorkbenchTask.MAX_ROWS) {
            hasTooManyRows = true;
            showTooManyRowsErrorDialog();
        } else {
            hasTooManyRows = false;
        }
        model = new PreviewTableModel(headers, tableData);
        table.setModel(model);
        table.setColumnSelectionAllowed(false);
        table.setRowSelectionAllowed(false);
        table.setCellSelectionEnabled(false);
        table.getTableHeader().setReorderingAllowed(false);
        table.setPreferredScrollableViewportSize(new Dimension(500, 100));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));

        model.fireTableDataChanged();
        model.fireTableStructureChanged();
        return table;

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataImportDialog.class, ex);
        log.error("Error attempting to parse input csv file:" + ex);
    }
    return null;
}