Example usage for javax.swing JTable setDefaultRenderer

List of usage examples for javax.swing JTable setDefaultRenderer

Introduction

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

Prototype

public void setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer) 

Source Link

Document

Sets a default cell renderer to be used if no renderer has been set in a TableColumn.

Usage

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

/**
 * Shows the future event list./*from   w  ww  .ja  v a 2 s  .  c om*/
 *
 * @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.specify.tasks.subpane.wb.DataImportDialog.java

/**
 * Parses the given import xls 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.//from   ww  w  .  j  a  v  a2 s .  c o  m
 * 
 * @param table - the table to display the data
 * @return JTable - the table to display the data
 */
private JTable setXLSTableData(final JTable table) {
    int numRows = 0;
    int numCols = 0;
    String[] headers = {};
    Vector<Vector<String>> tableDataVector = new Vector<Vector<String>>();
    Vector<String> rowData = new Vector<String>();
    Vector<String> headerVector = new Vector<String>();
    DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat");
    try {
        log.debug("setXLSTableData - file - " + configXLS.getFile().toString());

        InputStream input = new FileInputStream(configXLS.getFile());
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook workBook = new HSSFWorkbook(fs);
        HSSFSheet sheet = workBook.getSheetAt(0);

        Vector<Integer> badHeads = new Vector<Integer>();
        Vector<Integer> emptyCols = new Vector<Integer>();
        ((ConfigureXLS) config).checkHeadsAndCols(sheet, badHeads, emptyCols);
        if (badHeads.size() > 0 && doesFirstRowHaveHeaders) {
            if (table != null) {
                ((ConfigureXLS) config).showBadHeadingsMsg(badHeads, emptyCols, getTitle());
            }
            this.doesFirstRowHaveHeaders = false;
            try {
                ignoreActions = true;
                this.containsHeaders.setSelected(false);
            } finally {
                ignoreActions = false;
            }
            if (table != null) {
                return table;
            }
        }
        boolean firstRow = true;

        //quick fix to prevent ".0" at end of catalog numbers etc
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(20);
        nf.setGroupingUsed(false); //gets rid of commas

        int maxCols = 0;

        // Iterate over each row in the sheet
        Iterator<?> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            numCols = 0;
            rowData = new Vector<String>();
            HSSFRow row = (HSSFRow) rows.next();
            //log.debug(row.getLastCellNum()+"  "+row.getPhysicalNumberOfCells());
            int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
            if (maxSize > maxCols) {
                maxCols = maxSize;
            }
            while (numCols < maxSize) {
                if (emptyCols.indexOf(new Integer(numCols)) == -1) {
                    HSSFCell cell = row.getCell(numCols);
                    String value = null;
                    // if cell is blank, set value to ""
                    if (cell == null) {
                        value = "";
                    } else {
                        int type = cell.getCellType();

                        switch (type) {
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            // The best I can do at this point in the app is to guess if a
                            // cell is a date.
                            // Handle dates carefully while using HSSF. Excel stores all
                            // dates as numbers, internally.
                            // The only way to distinguish a date is by the formatting of
                            // the cell. (If you
                            // have ever formatted a cell containing a date in Excel, you
                            // will know what I mean.)
                            // Therefore, for a cell containing a date, cell.getCellType()
                            // will return
                            // HSSFCell.CELL_TYPE_NUMERIC. However, you can use a utility
                            // function,
                            // HSSFDateUtil.isCellDateFormatted(cell), to check if the cell
                            // can be a date.
                            // This function checks the format against a few internal
                            // formats to decide the issue,
                            // but by its very nature it is prone to false negatives.
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                                //value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                            } else {
                                double numeric = cell.getNumericCellValue();
                                value = nf.format(numeric);
                            }
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getRichStringCellValue().getString();
                            break;

                        case HSSFCell.CELL_TYPE_BLANK:
                            value = "";
                            break;

                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = Boolean.toString(cell.getBooleanCellValue());
                            break;

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = UIRegistry.getResourceString("WB_FORMULA_IMPORT_NO_PREVIEW");
                            break;

                        default:
                            value = "";
                            log.error("unsuported cell type");
                            break;
                        }
                    }
                    if (firstRow && doesFirstRowHaveHeaders) {
                        checkUserColInfo(value, numCols);
                    }
                    if (isUserCol(numCols)) {
                        rowData.add(value.toString());
                    }
                }
                numCols++;
            }
            if (doesFirstRowHaveHeaders && firstRow) {
                headerVector = rowData;
                headers = new String[rowData.size()];
            } else if (!doesFirstRowHaveHeaders && firstRow) {
                //headers = createDummyHeaders(rowData.size());
                tableDataVector.add(rowData);
            } else {
                tableDataVector.add(rowData);
            }
            firstRow = false;
            numRows++;
        }
        maxCols -= emptyCols.size();
        if (!doesFirstRowHaveHeaders) {
            headerVector = createDummyHeadersAsVector(maxCols);
            headers = new String[maxCols];
        }
        for (int i = 0; i < headerVector.size(); i++) {
            headers[i] = headerVector.elementAt(i);
        }
        printArray(headers);

        String[][] tableData = new String[tableDataVector.size()][maxCols];
        for (int i = 0; i < tableDataVector.size(); i++) {
            Vector<String> v = tableDataVector.get(i);
            for (int j = 0; j < v.size(); j++) {
                tableData[i][j] = v.get(j).toString();
            }

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

        if ((doesFirstRowHaveHeaders ? numRows - 1 : numRows) > WorkbenchTask.MAX_ROWS) {
            hasTooManyRows = true;
            showTooManyRowsErrorDialog();
        } else {
            hasTooManyRows = false;
        }
        log.debug(headers);
        log.debug(tableData);
        model = new PreviewTableModel(headers, tableData);
        JTable result = null;
        if (table == null) {
            result = new JTable();
            result.setColumnSelectionAllowed(false);
            result.setRowSelectionAllowed(false);
            result.setCellSelectionEnabled(false);
            result.getTableHeader().setReorderingAllowed(false);
            result.setPreferredScrollableViewportSize(new Dimension(500, 100));
            result.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        } else {
            result = table;
        }
        result.setModel(model);
        result.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
        model.fireTableDataChanged();
        model.fireTableStructureChanged();
        return result;
    } catch (Exception ex) {
        UIRegistry.displayErrorDlgLocalized(UIRegistry.getResourceString("WB_ERROR_READING_IMPORT_FILE"));
        if (table != null) {
            String[] columnNames = {};
            String[][] blankData = { {} };
            model = new PreviewTableModel(columnNames, blankData);
            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;
        }
        //log.error("Error attempting to parse input xls file:" + ex);
        //ex.printStackTrace();
    }

    return null;
}

From source file:fi.hoski.remote.ui.Admin.java

private void editReservations(final EventType eventType) {
    final Event event = chooseEvent(eventType, "CHOOSE");
    if (event != null) {
        final String eventTitle = TextUtil.getText(event.getEventType().name()) + " "
                + event.get(Event.EventDate);
        safeTitle = frame.getTitle();//from   w ww. j  ava  2 s .c o m
        frame.setTitle(eventTitle);
        reservationList = dss.getReservations(event);
        selectedReservations = new ArrayList<Reservation>();
        unSelectedReservations = new ArrayList<Reservation>();
        if (Event.isInspection(eventType)) {
            for (Reservation reservation : reservationList) {
                Boolean inspected = (Boolean) reservation.get(Reservation.INSPECTED);
                if (inspected != null && inspected) {
                    selectedReservations.add(reservation);
                } else {
                    unSelectedReservations.add(reservation);
                }
            }
        } else {
            for (Reservation reservation : reservationList) {
                Long order = (Long) reservation.get(Reservation.ORDER);
                if (order != null && order != 0) {
                    selectedReservations.add(reservation);
                } else {
                    unSelectedReservations.add(reservation);
                }
            }
        }
        DataObjectModel baseModel = Reservation.getModel(eventType);
        DataObjectModel unorderedModel = null;
        DataObjectModel orderedModel = null;
        switch (eventType) {
        case LAUNCH:
        case LIFT:
        case HULL_INSPECTION:
            unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
            orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
            break;
        case INSPECTION:
            unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR,
                    Reservation.EMAIL, Reservation.MOBILEPHONE, Reservation.DOCK, Reservation.DOCKNUMBER,
                    Reservation.INSPECTION_GASS, Reservation.INSPECTOR);
            orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR,
                    Reservation.EMAIL, Reservation.MOBILEPHONE, Reservation.DOCK, Reservation.DOCKNUMBER,
                    Reservation.NOTES);
            break;
        }

        final DataObjectListTableModel<Reservation> unorderedTableModel = new DataObjectListTableModel<Reservation>(
                unorderedModel, unSelectedReservations);
        final JTable unorderedtable = new FitTable(unorderedTableModel);
        TableSelectionHandler tsh1 = new TableSelectionHandler(unorderedtable);
        unorderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
        unorderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());

        unorderedtable.addKeyListener(unorderedTableModel.getRemover(dss));
        unorderedtable.setDragEnabled(true);
        unorderedtable.setDropMode(DropMode.INSERT_ROWS);
        TransferHandler unorderedTransferHandler = new DataObjectTransferHandler<Reservation>(
                unorderedTableModel);
        unorderedtable.setTransferHandler(unorderedTransferHandler);

        final DataObjectListTableModel<Reservation> orderedTableModel = new DataObjectListTableModel<Reservation>(
                orderedModel, selectedReservations);
        orderedTableModel.setEditable(Reservation.INSPECTION_CLASS, Reservation.INSPECTION_GASS,
                Reservation.BASICINSPECTION, Reservation.INSPECTOR);
        final JTable orderedtable = new FitTable(orderedTableModel);
        TableSelectionHandler tsh2 = new TableSelectionHandler(orderedtable);
        orderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
        orderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());

        orderedtable.addKeyListener(orderedTableModel.getRemover(dss));
        orderedtable.setDragEnabled(true);
        orderedtable.setDropMode(DropMode.INSERT_ROWS);
        TransferHandler orderedTransferHandler = new DataObjectTransferHandler<Reservation>(orderedTableModel);
        orderedtable.setTransferHandler(orderedTransferHandler);
        if (Event.isInspection(eventType)) {
            unorderedtable.setAutoCreateRowSorter(true);
            orderedtable.setAutoCreateRowSorter(true);
        }
        leftPane = new JScrollPane();
        leftPane.setViewport(new InfoViewport(TextUtil.getText(eventType.name() + "-leftPane")));
        leftPane.setViewportView(unorderedtable);
        leftPane.setTransferHandler(unorderedTransferHandler);

        rightPane = new JScrollPane();
        rightPane.setViewport(new InfoViewport(TextUtil.getText(eventType.name() + "-rightPane")));
        rightPane.setViewportView(orderedtable);
        rightPane.setTransferHandler(orderedTransferHandler);

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, rightPane);
        splitPane.setDividerLocation(0.5);
        menuReservation.setEnabled(false);
        safeContainer = frame.getContentPane();
        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.add(splitPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        JButton saveButton = new JButton();
        TextUtil.populate(saveButton, "SAVE");
        saveButton.setEnabled(!Event.isInspection(eventType));
        ActionListener saveAction = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                saveReservations();
            }
        };
        saveButton.addActionListener(saveAction);
        buttonPanel.add(saveButton);

        switch (eventType) {
        case INSPECTION: {
            if (privileged) {
                JButton inspectButton = new JButton();
                TextUtil.populate(inspectButton, "SET INSPECTED");
                ActionListener inspectAction = new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        TableCellEditor cellEditor = orderedtable.getCellEditor();
                        if (cellEditor != null) {
                            cellEditor.stopCellEditing();
                        }
                        try {
                            setAsInspected();
                        } catch (SQLException | ClassNotFoundException ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(null, ex.getMessage());
                        }
                    }
                };
                inspectButton.addActionListener(inspectAction);
                buttonPanel.add(inspectButton);
            }

            JButton addBoat = new JButton();
            TextUtil.populate(addBoat, "ADD BOAT");
            ActionListener addBoatAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Reservation reservation = reservate(eventType, event);
                    if (reservation != null) {
                        reservationList.add(reservation);
                        unSelectedReservations.add(reservation);
                        unorderedTableModel.fireTableDataChanged();
                    }
                }
            };
            addBoat.addActionListener(addBoatAction);
            buttonPanel.add(addBoat);

            JButton printTypeButton = new JButton();
            TextUtil.populate(printTypeButton, "PRINT");
            ActionListener printTypeAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printNameBoatTypeOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printTypeButton.addActionListener(printTypeAction);
            buttonPanel.add(printTypeButton);

            JButton printDockButton = new JButton();
            TextUtil.populate(printDockButton, "PRINT DOCK ORDER");
            ActionListener printDockAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printDockOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printDockButton.addActionListener(printDockAction);
            buttonPanel.add(printDockButton);

        }
            break;
        case HULL_INSPECTION: {
            JButton print = new JButton();
            TextUtil.populate(print, "PRINT");
            ActionListener printAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printAlphaOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            print.addActionListener(printAction);
            buttonPanel.add(print);

        }
            break;
        case LAUNCH:
        case LIFT: {
            JButton addBoat = new JButton();
            TextUtil.populate(addBoat, "ADD BOAT");
            ActionListener addBoatAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Reservation reservation = reservate(eventType, event);
                    if (reservation != null) {
                        reservationList.add(reservation);
                        unSelectedReservations.add(reservation);
                        unorderedTableModel.fireTableDataChanged();
                    }
                }
            };
            addBoat.addActionListener(addBoatAction);
            buttonPanel.add(addBoat);

            JButton printBrief = new JButton();
            TextUtil.populate(printBrief, "BRIEF PRINT");
            ActionListener printBriefAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printOrderBrief(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printBrief.addActionListener(printBriefAction);
            buttonPanel.add(printBrief);

            JButton print = new JButton();
            TextUtil.populate(print, "PRINT");
            ActionListener printAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        if (eventType == EventType.LAUNCH) {
                            printLaunchOrder(eventTitle);
                        } else {
                            printLiftOrder(eventTitle);
                        }
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            print.addActionListener(printAction);
            buttonPanel.add(print);
        }
            break;
        }

        JButton cancelButton = new JButton();
        TextUtil.populate(cancelButton, "CANCEL");
        ActionListener cancelAction = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                cancel();
            }
        };
        cancelButton.addActionListener(cancelAction);
        buttonPanel.add(cancelButton);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setVisible(true);
        KeyListener keyListener = new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 10) {
                    int selectedRow = unorderedtable.getSelectedRow();
                    if (selectedRow != -1) {
                        RowSorter<? extends TableModel> rowSorter = unorderedtable.getRowSorter();
                        if (rowSorter != null) {
                            selectedRow = rowSorter.convertRowIndexToModel(selectedRow);
                        }
                        Reservation reservation = unorderedTableModel.getObject(selectedRow);
                        orderedTableModel.add(reservation);
                        unorderedTableModel.remove(reservation);
                        e.consume();
                        unorderedtable.changeSelection(selectedRow, 0, false, false);
                    }
                }
            }
        };
        unorderedtable.addKeyListener(keyListener);
        unorderedtable.requestFocusInWindow();
    }
}

From source file:org.esa.beam.visat.toolviews.stat.StatisticsPanel.java

private JPanel createStatPanel(Stx stx, final Mask regionalMask, final Mask qualityMask, int stxIdx,
        RasterDataNode raster) {/* w ww. j  av a 2s  .co m*/

    final Histogram histogram = stx.getHistogram();
    final int row = stxIdx + 1; // account for header

    boolean includeFileMetaData = statisticsCriteriaPanel.isIncludeFileMetaData();
    boolean includeMaskMetaData = statisticsCriteriaPanel.isIncludeMaskMetaData();
    boolean includeBandMetaData = statisticsCriteriaPanel.isIncludeBandMetaData();
    boolean includeBinningInfo = statisticsCriteriaPanel.isIncludeBinningInfo();
    ;
    boolean includeTimeMetaData = statisticsCriteriaPanel.isIncludeTimeMetaData();
    boolean isIncludeTimeSeriesMetaData = statisticsCriteriaPanel.isIncludeTimeSeriesMetaData();
    boolean includeProjectionParameters = statisticsCriteriaPanel.isIncludeProjectionParameters();
    boolean includeColumnBreaks = statisticsCriteriaPanel.isIncludeColBreaks();

    // Initialize all spreadsheet table indices to -1 (default don't use value)
    if (stxIdx == 0 || metaDataFieldsHashMap == null || primaryStatisticsFieldsHashMap == null) {
        initHashMaps();
    }

    XIntervalSeries histogramSeries = new XIntervalSeries("Histogram");
    double histDomainBounds[] = { histogram.getLowValue(0), histogram.getHighValue(0) };
    double histRangeBounds[] = { Double.NaN, Double.NaN };

    if (!fixedHistDomainAllPlots || (fixedHistDomainAllPlots && !fixedHistDomainAllPlotsInitialized)) {
        if (!statisticsCriteriaPanel.isLogMode()) {
            if (statisticsCriteriaPanel.plotsThreshDomainSpan()) {

                if (statisticsCriteriaPanel.plotsThreshDomainLow() >= 0.1) {
                    histDomainBounds[0] = histogram
                            .getPTileThreshold((statisticsCriteriaPanel.plotsThreshDomainLow()) / 100)[0];
                }

                if (statisticsCriteriaPanel.plotsThreshDomainHigh() <= 99.9) {
                    histDomainBounds[1] = histogram
                            .getPTileThreshold(statisticsCriteriaPanel.plotsThreshDomainHigh() / 100)[0];
                }

            } else if (statisticsCriteriaPanel.plotsDomainSpan()) {
                if (!Double.isNaN(statisticsCriteriaPanel.plotsDomainLow())) {
                    histDomainBounds[0] = statisticsCriteriaPanel.plotsDomainLow();
                }
                if (!Double.isNaN(statisticsCriteriaPanel.plotsDomainHigh())) {
                    histDomainBounds[1] = statisticsCriteriaPanel.plotsDomainHigh();
                }
            }

        } else {
            histDomainBounds[0] = histogram.getBinLowValue(0, 0);
            histDomainBounds[1] = histogram.getHighValue(0);
        }

        //            if (!LogMode && plotsThreshDomainSpan && plotsThreshDomainLow >= 0.1 && plotsThreshDomainHigh <= 99.9) {
        //                histDomainBounds[0] = histogram.getPTileThreshold((plotsThreshDomainLow) / 100)[0];
        //                histDomainBounds[1] = histogram.getPTileThreshold(plotsThreshDomainHigh / 100)[0];
        //
        //            } else {
        //                histDomainBounds[0] = histogram.getBinLowValue(0, 0);
        //                histDomainBounds[1] = histogram.getHighValue(0);
        //            }

        if (fixedHistDomainAllPlots && !fixedHistDomainAllPlotsInitialized) {
            histDomainBoundsAllPlots[0] = histDomainBounds[0];
            histDomainBoundsAllPlots[1] = histDomainBounds[1];
            fixedHistDomainAllPlotsInitialized = true;
        }
    } else {
        histDomainBounds[0] = histDomainBoundsAllPlots[0];
        histDomainBounds[1] = histDomainBoundsAllPlots[1];
    }

    int[] bins = histogram.getBins(0);
    for (int j = 0; j < bins.length; j++) {

        histogramSeries.add(histogram.getBinLowValue(0, j), histogram.getBinLowValue(0, j),
                j < bins.length - 1 ? histogram.getBinLowValue(0, j + 1) : histogram.getHighValue(0), bins[j]);
    }

    String logTitle = (statisticsCriteriaPanel.isLogMode()) ? "Log10 of " : "";

    ChartPanel histogramPanel = createChartPanel(histogramSeries,
            logTitle + raster.getName() + " (" + raster.getUnit() + ")", "Frequency in #Pixels",
            new Color(0, 0, 127), histDomainBounds, histRangeBounds);

    //  histogramPanel.setPreferredSize(new Dimension(300, 200));

    if (statisticsCriteriaPanel.exactPlotSize()) {
        histogramPanel.setMinimumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(),
                statisticsCriteriaPanel.plotSizeHeight()));
        histogramPanel.setPreferredSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(),
                statisticsCriteriaPanel.plotSizeHeight()));
        histogramPanel.setMaximumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(),
                statisticsCriteriaPanel.plotSizeHeight()));
    } else {
        histogramPanel.setMinimumSize(new Dimension(plotMinWidth, plotMinHeight));
        histogramPanel.setPreferredSize(new Dimension(plotMinWidth, plotMinHeight));
    }

    XIntervalSeries percentileSeries = new XIntervalSeries("Percentile");

    //        if (1 == 2 && LogMode) {
    //            percentileSeries.add(0,
    //                    0,
    //                    1,
    //                    Math.pow(10, histogram.getLowValue(0)));
    //            for (int j = 1; j < 99; j++) {
    //                percentileSeries.add(j,
    //                        j,
    //                        j + 1,
    //                        Math.pow(10, histogram.getPTileThreshold(j / 100.0)[0]));
    //            }
    //            percentileSeries.add(99,
    //                    99,
    //                    100,
    //                    Math.pow(10, histogram.getHighValue(0)));
    //
    //        } else {
    //            percentileSeries.add(0,
    //                    0,
    //                    0.25,
    //                    histogram.getLowValue(0));
    //
    //            for (double j = 0.25; j < 99.75; j += .25) {
    //                percentileSeries.add(j,
    //                        j,
    //                        j + 1,
    //                        histogram.getPTileThreshold(j / 100.0)[0]);
    //            }
    //            percentileSeries.add(99.75,
    //                    99.75,
    //                    100,
    //                    histogram.getHighValue(0));
    //        }

    //
    //        double fraction = 0;
    //        for (int j = 0; j < bins.length; j++) {
    //
    //             fraction = (1.0) * j / bins.length;
    //
    //            if (fraction > 0 && fraction < 1) {
    //                percentileSeries.add(histogram.getBinLowValue(0, j),
    //                        histogram.getBinLowValue(0, j),
    //                        j < bins.length - 1 ? histogram.getBinLowValue(0, j + 1) : histogram.getHighValue(0),
    //                        histogram.getPTileThreshold(fraction)[0]);
    //            }
    //
    //
    //        }
    //
    //        double test = fraction;

    double[] percentileDomainBounds = { Double.NaN, Double.NaN };
    double[] percentileRangeBounds = { Double.NaN, Double.NaN };
    ChartPanel percentilePanel = null;

    if (invertPercentile) {

        double increment = .01;
        for (double j = 0; j < 100; j += increment) {
            double fraction = j / 100.0;
            double nextFraction = (j + increment) / 100.0;

            if (fraction > 0.0 && fraction < 1.0 && nextFraction > 0.0 && nextFraction < 1.0) {
                double thresh = histogram.getPTileThreshold(fraction)[0];
                double nextThresh = histogram.getPTileThreshold(nextFraction)[0];

                percentileSeries.add(thresh, thresh, nextThresh, j);
            }
        }

        if (!statisticsCriteriaPanel.isLogMode()) {
            percentileDomainBounds[0] = histDomainBounds[0];
            percentileDomainBounds[1] = histDomainBounds[1];
        }
        percentileRangeBounds[0] = 0;
        percentileRangeBounds[1] = 100;

        percentilePanel = createScatterChartPanel(percentileSeries,
                logTitle + raster.getName() + " (" + raster.getUnit() + ")", "Percent Threshold",
                new Color(0, 0, 0), percentileDomainBounds, percentileRangeBounds);

    } else {
        percentileSeries.add(0, 0, 0.25, histogram.getLowValue(0));

        for (double j = 0.25; j < 99.75; j += .25) {
            percentileSeries.add(j, j, j + 1, histogram.getPTileThreshold(j / 100.0)[0]);
        }
        percentileSeries.add(99.75, 99.75, 100, histogram.getHighValue(0));

        percentileDomainBounds[0] = 0;
        percentileDomainBounds[1] = 100;
        percentileRangeBounds[0] = histDomainBounds[0];
        percentileRangeBounds[1] = histDomainBounds[1];

        percentilePanel = createScatterChartPanel(percentileSeries, "Percent_Threshold",
                logTitle + raster.getName() + " (" + raster.getUnit() + ")", new Color(0, 0, 0),
                percentileDomainBounds, percentileRangeBounds);

    }

    //   percentilePanel.setPreferredSize(new Dimension(300, 200));
    if (statisticsCriteriaPanel.exactPlotSize()) {
        percentilePanel.setMinimumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(),
                statisticsCriteriaPanel.plotSizeHeight()));
        percentilePanel.setPreferredSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(),
                statisticsCriteriaPanel.plotSizeHeight()));
        percentilePanel.setMaximumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(),
                statisticsCriteriaPanel.plotSizeHeight()));
    } else {
        percentilePanel.setMinimumSize(new Dimension(plotMinWidth, plotMinHeight));
        percentilePanel.setPreferredSize(new Dimension(plotMinWidth, plotMinHeight));
    }

    int size = raster.getRasterHeight() * raster.getRasterWidth();

    int validPixelCount = histogram.getTotals()[0];

    int dataRows = 0;

    //                new Object[]{"RasterSize(Pixels)", size},
    //                new Object[]{"SampleSize(Pixels)", histogram.getTotals()[0]},

    Object[][] totalPixels = null;

    if (statisticsCriteriaPanel.includeTotalPixels()) {
        int totalPixelCount = stx.getRawTotal();
        double percentFilled = (totalPixelCount > 0) ? (1.0 * validPixelCount / totalPixelCount) : 0;

        totalPixels = new Object[][] { new Object[] { "Regional_Pixels", stx.getRawTotal() },
                new Object[] { "Valid_Pixels", validPixelCount },
                new Object[] { "Fraction_Valid", percentFilled } };

    } else {
        totalPixels = new Object[][] { new Object[] { "Valid_Pixels", validPixelCount } };
    }
    dataRows += totalPixels.length;

    Object[][] firstData = new Object[][] { new Object[] { "Mean", stx.getMean() } };
    dataRows += firstData.length;

    Object[][] minMaxData = null;
    if (statisticsCriteriaPanel.includeMinMax()) {
        minMaxData = new Object[][] { new Object[] { "Minimum", stx.getMinimum() },
                new Object[] { "Maximum", stx.getMaximum() } };
        dataRows += minMaxData.length;
    }

    Object[] medianObject = null;

    if (statisticsCriteriaPanel.includeMedian()) {
        medianObject = new Object[] { "Median", stx.getMedianRaster() };

        dataRows++;
    }

    Object[][] secondData = new Object[][] { new Object[] { "Standard_Deviation", stx.getStandardDeviation() },
            new Object[] { "Variance", getVariance(stx) },
            new Object[] { "Coefficient_of_Variation", getCoefficientOfVariation(stx) } };
    dataRows += secondData.length;

    Object[][] binningInfo = null;
    if (statisticsCriteriaPanel.isIncludeBinningInfo()) {
        binningInfo = new Object[][] { new Object[] { "Total_Bins", histogram.getNumBins()[0] },
                new Object[] { "Bin_Width", getBinSize(histogram) },
                new Object[] { "Bin_Min", histogram.getLowValue(0) },
                new Object[] { "Bin_Max", histogram.getHighValue(0) } };

        dataRows += binningInfo.length;
    }

    Object[][] histogramStats = null;
    if (statisticsCriteriaPanel.includeHistogramStats()) {
        if (statisticsCriteriaPanel.isLogMode()) {
            histogramStats = new Object[][] {
                    new Object[] { "Mean(LogBinned)", Math.pow(10, histogram.getMean()[0]) },
                    new Object[] { "Median(LogBinned)", Math.pow(10, stx.getMedian()) },
                    new Object[] { "StandardDeviation(LogBinned)",
                            Math.pow(10, histogram.getStandardDeviation()[0]) } };
        } else {
            histogramStats = new Object[][] { new Object[] { "Mean(Binned)", histogram.getMean()[0] },
                    new Object[] { "Median(Binned)", stx.getMedian() },
                    new Object[] { "StandardDeviation(Binned)", histogram.getStandardDeviation()[0] } };
        }
        dataRows += histogramStats.length;
    }

    Object[][] percentData = new Object[statisticsCriteriaPanel.getPercentThresholdsList().size()][];
    for (int i = 0; i < statisticsCriteriaPanel.getPercentThresholdsList().size(); i++) {
        int value = statisticsCriteriaPanel.getPercentThresholdsList().get(i);
        double percent = value / 100.0;
        String percentString = Integer.toString(value);

        Object[] pTileThreshold;
        if (statisticsCriteriaPanel.isLogMode()) {
            pTileThreshold = new Object[] { percentString + "%Threshold(Log)",
                    Math.pow(10, histogram.getPTileThreshold(percent)[0]) };
        } else {
            pTileThreshold = new Object[] { percentString + "%Threshold",
                    histogram.getPTileThreshold(percent)[0] };
        }
        percentData[i] = pTileThreshold;
    }
    dataRows += percentData.length;

    Object[][] tableData = new Object[dataRows][];
    int tableDataIdx = 0;

    if (totalPixels != null) {
        for (int i = 0; i < totalPixels.length; i++) {
            tableData[tableDataIdx] = totalPixels[i];
            tableDataIdx++;
        }
    }

    if (firstData != null) {
        for (int i = 0; i < firstData.length; i++) {
            tableData[tableDataIdx] = firstData[i];
            tableDataIdx++;
        }
    }

    if (medianObject != null) {
        tableData[tableDataIdx] = medianObject;
        tableDataIdx++;
    }

    if (minMaxData != null) {
        for (int i = 0; i < minMaxData.length; i++) {
            tableData[tableDataIdx] = minMaxData[i];
            tableDataIdx++;
        }
    }

    if (secondData != null) {
        for (int i = 0; i < secondData.length; i++) {
            tableData[tableDataIdx] = secondData[i];
            tableDataIdx++;
        }
    }

    if (binningInfo != null) {
        for (int i = 0; i < binningInfo.length; i++) {
            tableData[tableDataIdx] = binningInfo[i];
            tableDataIdx++;
        }
    }

    if (histogramStats != null) {
        for (int i = 0; i < histogramStats.length; i++) {
            tableData[tableDataIdx] = histogramStats[i];
            tableDataIdx++;
        }
    }

    if (percentData != null) {
        for (int i = 0; i < percentData.length; i++) {
            tableData[tableDataIdx] = percentData[i];
            tableDataIdx++;
        }
    }

    numStxFields = tableData.length;

    int fieldIdx = 0;

    // Initialize indices
    if (stxIdx == 0) {

        primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.FileRefNum, fieldIdx);
        fieldIdx++;
        primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.BandName, fieldIdx);
        fieldIdx++;
        primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.MaskName, fieldIdx);
        fieldIdx++;
        primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.QualityMaskName, fieldIdx);
        fieldIdx++;

        stxFieldsStartIdx = fieldIdx;
        fieldIdx += numStxFields;
        stxFieldsEndIdx = fieldIdx - 1;
        if (includeBandMetaData) {
            if (includeColumnBreaks) {
                metaDataFieldsHashMap.put(MetaDataFields.BandMetaDataBreak, fieldIdx);
                fieldIdx++;
            }
            metaDataFieldsHashMap.put(MetaDataFields.BandName, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.BandUnit, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.BandValidExpression, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.BandDescription, fieldIdx);
            fieldIdx++;

        }

        if (includeMaskMetaData) {
            if (includeColumnBreaks) {
                metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskMetaDataBreak, fieldIdx);
                fieldIdx++;
            }
            metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskName, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskDescription, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskExpression, fieldIdx);
            fieldIdx++;

            if (includeColumnBreaks) {
                metaDataFieldsHashMap.put(MetaDataFields.QualityMaskMetaDataBreak, fieldIdx);
                fieldIdx++;
            }
            metaDataFieldsHashMap.put(MetaDataFields.QualityMaskName, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.QualityMaskDescription, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.QualityMaskExpression, fieldIdx);
            fieldIdx++;
        }

        if (includeTimeMetaData || isIncludeTimeSeriesMetaData) {
            if (includeColumnBreaks) {
                metaDataFieldsHashMap.put(MetaDataFields.TimeMetaDataBreak, fieldIdx);
                fieldIdx++;
            }

            if (includeTimeMetaData) {
                metaDataFieldsHashMap.put(MetaDataFields.StartDate, fieldIdx);
                fieldIdx++;
                metaDataFieldsHashMap.put(MetaDataFields.StartTime, fieldIdx);
                fieldIdx++;
                metaDataFieldsHashMap.put(MetaDataFields.EndDate, fieldIdx);
                fieldIdx++;
                metaDataFieldsHashMap.put(MetaDataFields.EndTime, fieldIdx);
                fieldIdx++;
            }

            if (isIncludeTimeSeriesMetaData) {
                metaDataFieldsHashMap.put(MetaDataFields.TimeSeriesDate, fieldIdx);
                fieldIdx++;
                metaDataFieldsHashMap.put(MetaDataFields.TimeSeriesTime, fieldIdx);
                fieldIdx++;
            }
        }

        if (includeFileMetaData) {
            if (includeColumnBreaks) {
                metaDataFieldsHashMap.put(MetaDataFields.FileMetaDataBreak, fieldIdx);
                fieldIdx++;
            }
            metaDataFieldsHashMap.put(MetaDataFields.FileName, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.FileType, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.FileFormat, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.FileWidth, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.FileHeight, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.Sensor, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.Platform, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.Resolution, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.DayNight, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.Orbit, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.ProcessingVersion, fieldIdx);
            fieldIdx++;
            metaDataFieldsHashMap.put(MetaDataFields.Projection, fieldIdx);
            fieldIdx++;

        }

        if (includeProjectionParameters) {
            metaDataFieldsHashMap.put(MetaDataFields.ProjectionParameters, fieldIdx);
            fieldIdx++;
        }

    }

    if (statsSpreadsheet == null) {
        statsSpreadsheet = new Object[numStxRegions + 2][fieldIdx];
        // add 1 row to account for the header and 1 more empty row because JTable for some reason displays
        // only half of the last row when row count is large
    }

    String startDateString = "";
    String startTimeString = "";
    String endDateString = "";
    String endTimeString = "";

    if (includeTimeMetaData) {
        ProductData.UTC startDateTimeCorrected;
        ProductData.UTC endDateTimeCorrected;

        // correct time (invert start and end time if end time later than start time
        if (getProduct().getStartTime() != null && getProduct().getEndTime() != null) {
            if (getProduct().getStartTime().getMJD() <= getProduct().getEndTime().getMJD()) {

                startDateTimeCorrected = getProduct().getStartTime();
                endDateTimeCorrected = getProduct().getEndTime();
            } else {

                startDateTimeCorrected = getProduct().getEndTime();
                endDateTimeCorrected = getProduct().getStartTime();
            }

            if (startDateTimeCorrected != null) {
                String[] startDateTimeStringArray = startDateTimeCorrected.toString().split(" ");
                if (startDateTimeStringArray.length >= 2) {
                    startDateString = startDateTimeStringArray[0].trim();
                    startTimeString = startDateTimeStringArray[1].trim();
                }
            }

            if (endDateTimeCorrected != null) {
                String[] endDateTimeStringArray = endDateTimeCorrected.toString().split(" ");
                if (endDateTimeStringArray.length >= 2) {
                    endDateString = endDateTimeStringArray[0].trim();
                    endTimeString = endDateTimeStringArray[1].trim();
                }
            }
        }
    }

    String timeSeriesDate = "";
    String timeSeriesTime = "";
    if (isIncludeTimeSeriesMetaData) {
        String bandName = raster.getName();

        String productDateTime = convertBandNameToProductTime(bandName);

        if (productDateTime != null) {
            String[] endDateTimeStringArray = productDateTime.split(" ");
            if (endDateTimeStringArray.length >= 2) {
                timeSeriesDate = endDateTimeStringArray[0].trim();
                timeSeriesTime = endDateTimeStringArray[1].trim();
            }
        }
    }

    String maskName = "";
    String maskDescription = "";
    String maskExpression = "";
    if (regionalMask != null) {
        maskName = regionalMask.getName();
        maskDescription = regionalMask.getDescription();
        maskExpression = regionalMask.getImageConfig().getValue("expression");
    }

    String qualityMaskName = "";
    String qualityMaskDescription = "";
    String qualityMaskExpression = "";
    if (qualityMask != null) {
        qualityMaskName = qualityMask.getName();
        qualityMaskDescription = qualityMask.getDescription();
        qualityMaskExpression = qualityMask.getImageConfig().getValue("expression");
    }

    addFieldToSpreadsheet(row, PrimaryStatisticsFields.FileRefNum, getProduct().getRefNo());
    addFieldToSpreadsheet(row, PrimaryStatisticsFields.BandName, raster.getName());
    addFieldToSpreadsheet(row, PrimaryStatisticsFields.MaskName, maskName);
    addFieldToSpreadsheet(row, PrimaryStatisticsFields.QualityMaskName, qualityMaskName);

    addFieldToSpreadsheet(row, MetaDataFields.TimeMetaDataBreak, COLUMN_BREAK);
    addFieldToSpreadsheet(row, MetaDataFields.StartDate, startDateString);
    addFieldToSpreadsheet(row, MetaDataFields.StartTime, startTimeString);
    addFieldToSpreadsheet(row, MetaDataFields.EndDate, endDateString);
    addFieldToSpreadsheet(row, MetaDataFields.EndTime, endTimeString);

    addFieldToSpreadsheet(row, MetaDataFields.TimeSeriesDate, timeSeriesDate);
    addFieldToSpreadsheet(row, MetaDataFields.TimeSeriesTime, timeSeriesTime);

    addFieldToSpreadsheet(row, MetaDataFields.FileMetaDataBreak, COLUMN_BREAK);
    addFieldToSpreadsheet(row, MetaDataFields.FileName, getProduct().getName());
    addFieldToSpreadsheet(row, MetaDataFields.FileType, getProduct().getProductType());
    addFieldToSpreadsheet(row, MetaDataFields.FileWidth, getProduct().getSceneRasterWidth());
    addFieldToSpreadsheet(row, MetaDataFields.FileFormat, getProductFormatName(getProduct()));
    addFieldToSpreadsheet(row, MetaDataFields.FileHeight, getProduct().getSceneRasterHeight());
    addFieldToSpreadsheet(row, MetaDataFields.Sensor,
            ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_SENSOR_KEYS));
    addFieldToSpreadsheet(row, MetaDataFields.Platform,
            ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_PLATFORM_KEYS));
    addFieldToSpreadsheet(row, MetaDataFields.Resolution,
            ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_RESOLUTION_KEYS));
    addFieldToSpreadsheet(row, MetaDataFields.DayNight,
            ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_DAY_NIGHT_KEYS));
    addFieldToSpreadsheet(row, MetaDataFields.Orbit, ProductUtils.getMetaDataOrbit(getProduct()));
    addFieldToSpreadsheet(row, MetaDataFields.ProcessingVersion,
            ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_PROCESSING_VERSION_KEYS));

    // Determine projection
    String projection = "";
    String projectionParameters = "";
    GeoCoding geo = getProduct().getGeoCoding();
    // determine if using class CrsGeoCoding otherwise display class
    if (geo != null) {
        if (geo instanceof CrsGeoCoding) {
            projection = geo.getMapCRS().getName().toString() + "(obtained from CrsGeoCoding)";
            projectionParameters = geo.getMapCRS().toString().replaceAll("\n", " ").replaceAll(" ", "");
        } else if (geo.toString() != null) {
            String projectionFromMetaData = ProductUtils.getMetaData(getProduct(),
                    ProductUtils.METADATA_POSSIBLE_PROJECTION_KEYS);

            if (projectionFromMetaData != null && projectionFromMetaData.length() > 0) {
                projection = projectionFromMetaData + "(obtained from MetaData)";
            } else {
                projection = "unknown (" + geo.getClass().toString() + ")";
            }
        }
    }
    addFieldToSpreadsheet(row, MetaDataFields.Projection, projection);
    addFieldToSpreadsheet(row, MetaDataFields.ProjectionParameters, projectionParameters);

    addFieldToSpreadsheet(row, MetaDataFields.BandMetaDataBreak, COLUMN_BREAK);
    addFieldToSpreadsheet(row, MetaDataFields.BandName, raster.getName());
    addFieldToSpreadsheet(row, MetaDataFields.BandUnit, raster.getUnit());
    addFieldToSpreadsheet(row, MetaDataFields.BandValidExpression, raster.getValidPixelExpression());
    addFieldToSpreadsheet(row, MetaDataFields.BandDescription, raster.getDescription());

    addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskMetaDataBreak, COLUMN_BREAK);
    addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskName, maskName);
    addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskDescription, maskDescription);
    addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskExpression, maskExpression);

    addFieldToSpreadsheet(row, MetaDataFields.QualityMaskMetaDataBreak, COLUMN_BREAK);
    addFieldToSpreadsheet(row, MetaDataFields.QualityMaskName, qualityMaskName);
    addFieldToSpreadsheet(row, MetaDataFields.QualityMaskDescription, qualityMaskDescription);
    addFieldToSpreadsheet(row, MetaDataFields.QualityMaskExpression, qualityMaskExpression);

    // Add Header first time through
    if (row <= 1) {

        int k = stxFieldsStartIdx;
        for (int i = 0; i < tableData.length; i++) {
            Object value = tableData[i][0];

            if (k < statsSpreadsheet[0].length && k <= stxFieldsEndIdx) {
                statsSpreadsheet[0][k] = value;
                k++;
            }
        }

    }

    // account for header as added row
    if (row < statsSpreadsheet.length) {

        int k = stxFieldsStartIdx;
        for (int i = 0; i < tableData.length; i++) {
            Object value = tableData[i][1];

            if (k < statsSpreadsheet[row].length && k <= stxFieldsEndIdx) {
                statsSpreadsheet[row][k] = value;
                k++;
            }
        }

    }

    int numPlots = 0;
    if (statisticsCriteriaPanel.showPercentPlots()) {
        numPlots++;
    }

    if (statisticsCriteriaPanel.showHistogramPlots()) {
        numPlots++;
    }

    JPanel plotContainerPanel = null;

    if (numPlots > 0) {
        plotContainerPanel = new JPanel(new GridLayout(1, numPlots));

        if (statisticsCriteriaPanel.showHistogramPlots()) {
            plotContainerPanel.add(histogramPanel);
        }

        if (statisticsCriteriaPanel.showPercentPlots()) {
            plotContainerPanel.add(percentilePanel);
        }
    }

    TableModel tableModel = new DefaultTableModel(tableData, new String[] { "Name", "Value" }) {
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnIndex == 0 ? String.class : Number.class;
        }

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

    final JTable table = new JTable(tableModel);
    table.setDefaultRenderer(Number.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            final Component label = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            if (value instanceof Float || value instanceof Double) {
                setHorizontalTextPosition(RIGHT);
                setText(getFormattedValue((Number) value));
            }
            return label;
        }

        private String getFormattedValue(Number value) {
            if (value.doubleValue() < 0.001 && value.doubleValue() > -0.001 && value.doubleValue() != 0.0) {
                return new DecimalFormat("0.####E0").format(value.doubleValue());
            }
            String format = "%." + Integer.toString(statisticsCriteriaPanel.decimalPlaces()) + "f";

            return String.format(format, value.doubleValue());
        }
    });
    table.addMouseListener(popupHandler);

    // TEST CODE generically preferred size of each column based on longest expected entry
    // fails a bit because decimal formatting is not captured
    // stub of code commented out in case we want to make it work
    // meanwhile longest entry is being used SEE below

    //        int column0Length = 0;
    //        int column1Length = 0;
    //        FontMetrics fm = table.getFontMetrics(table.getFont());
    //        for (int rowIndex = 0; rowIndex < table.getRowCount(); rowIndex++) {
    //            String test = table.getValueAt(rowIndex,0).toString();
    //            int currColumn0Length = fm.stringWidth(table.getValueAt(rowIndex,0).toString());
    //            if (currColumn0Length > column0Length) {
    //                column0Length = currColumn0Length;
    //            }
    //
    //            String test2 = table.getValueAt(rowIndex,1).toString();
    //            int currColumn1Length = fm.stringWidth(table.getValueAt(rowIndex,1).toString());
    //            if (currColumn1Length > column1Length) {
    //                column1Length = currColumn1Length;
    //            }
    //        }

    // Set preferred size of each column based on longest expected entry
    FontMetrics fm = table.getFontMetrics(table.getFont());
    TableColumn column = null;
    int col1PreferredWidth = -1;
    if (statisticsCriteriaPanel.isLogMode()) {
        col1PreferredWidth = fm.stringWidth("StandardDeviation(LogBinned):") + 10;
    } else {
        col1PreferredWidth = fm.stringWidth("StandardDeviation(Binned):") + 10;
    }

    // int col1PreferredWidth = fm.stringWidth("wwwwwwwwwwwwwwwwwwwwwwwwww");
    int col2PreferredWidth = fm.stringWidth("1234567890") + 10;
    int tablePreferredWidth = col1PreferredWidth + col2PreferredWidth;
    for (int i = 0; i < 2; i++) {
        column = table.getColumnModel().getColumn(i);
        if (i == 0) {
            column.setPreferredWidth(col1PreferredWidth);
            column.setMaxWidth(col1PreferredWidth);
        } else {
            column.setPreferredWidth(col2PreferredWidth);
        }
    }

    JPanel textContainerPanel = new JPanel(new BorderLayout(2, 2));
    //   textContainerPanel.setBackground(Color.WHITE);
    textContainerPanel.add(table, BorderLayout.CENTER);
    textContainerPanel.addMouseListener(popupHandler);

    JPanel statsPane = GridBagUtils.createPanel();
    GridBagConstraints gbc = GridBagUtils.createConstraints("");
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.weightx = 1;
    gbc.weighty = 1;

    Dimension dim = table.getPreferredSize();
    table.setPreferredSize(new Dimension(tablePreferredWidth, dim.height));
    statsPane.add(table, gbc);
    statsPane.setPreferredSize(new Dimension(tablePreferredWidth, dim.height));

    JPanel plotsPane = null;

    if (plotContainerPanel != null) {
        plotsPane = GridBagUtils.createPanel();
        plotsPane.setBackground(Color.WHITE);
        //    plotsPane.setBorder(UIUtils.createGroupBorder(" ")); /*I18N*/
        GridBagConstraints gbcPlots = GridBagUtils.createConstraints("");
        gbcPlots.gridy = 0;
        if (statisticsCriteriaPanel.exactPlotSize()) {
            gbcPlots.fill = GridBagConstraints.NONE;
        } else {
            gbcPlots.fill = GridBagConstraints.BOTH;
        }

        gbcPlots.anchor = GridBagConstraints.NORTHWEST;
        gbcPlots.weightx = 0.5;
        gbcPlots.weighty = 1;
        plotsPane.add(plotContainerPanel, gbcPlots);
    }

    JPanel mainPane = GridBagUtils.createPanel();
    mainPane.setBorder(UIUtils.createGroupBorder(getSubPanelTitle(regionalMask, qualityMask, raster))); /*I18N*/
    GridBagConstraints gbcMain = GridBagUtils.createConstraints("");
    gbcMain.gridx = 0;
    gbcMain.gridy = 0;
    gbcMain.anchor = GridBagConstraints.NORTHWEST;
    if (plotsPane != null) {
        gbcMain.fill = GridBagConstraints.VERTICAL;
        gbcMain.weightx = 0;
    } else {
        gbcMain.fill = GridBagConstraints.BOTH;
        gbcMain.weightx = 1;
    }

    if (statisticsCriteriaPanel.showStatsList()) {
        gbcMain.weighty = 1;
        mainPane.add(statsPane, gbcMain);
        gbcMain.gridx++;
    }

    gbcMain.weightx = 1;
    gbcMain.weighty = 1;
    gbcMain.fill = GridBagConstraints.BOTH;

    if (plotsPane != null) {
        mainPane.add(plotsPane, gbcMain);
    }

    return mainPane;
}

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   www  . j a  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.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/*ww  w.ja  va2  s  . c  om*/
        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:edu.ku.brc.specify.extras.ViewToSchemaReview.java

/**
 * /* www.j a v a  2 s.  c  o  m*/
 */
public void checkSchemaAndViews() {

    Hashtable<String, HashSet<String>> viewFieldHash = new Hashtable<String, HashSet<String>>();

    SpecifyAppContextMgr sacm = (SpecifyAppContextMgr) AppContextMgr.getInstance();

    for (ViewIFace view : sacm.getEntirelyAllViews()) {
        //System.err.println(view.getName() + " ----------------------");
        for (AltViewIFace av : view.getAltViews()) {
            ViewDefIFace vd = av.getViewDef();
            if (vd.getType() == ViewType.form) {
                DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(vd.getClassName());
                if (ti != null) {
                    HashSet<String> tiHash = viewFieldHash.get(ti.getName());
                    if (tiHash == null) {
                        tiHash = new HashSet<String>();
                        viewFieldHash.put(ti.getName(), tiHash);
                    }

                    FormViewDef fvd = (FormViewDef) vd;
                    for (FormRowIFace row : fvd.getRows()) {
                        for (FormCellIFace cell : row.getCells()) {
                            if (cell.getType() == FormCellIFace.CellType.panel) {
                                FormCellPanelIFace panelCell = (FormCellPanelIFace) cell;
                                for (String fieldName : panelCell.getFieldNames()) {
                                    tiHash.add(fieldName);
                                }

                            } else if (cell.getType() == FormCellIFace.CellType.field
                                    || cell.getType() == FormCellIFace.CellType.subview) {
                                String fieldName = cell.getName();
                                if (!cell.isIgnoreSetGet() && !fieldName.equals("this")) {
                                    DBFieldInfo fi = ti.getFieldByName(fieldName);
                                    if (fi != null) {
                                        //System.err.println("Form Field["+fieldName+"] is in schema.");
                                        tiHash.add(fieldName);
                                    } else {
                                        DBRelationshipInfo ri = ti.getRelationshipByName(fieldName);
                                        if (ri == null) {
                                            //System.err.println("Form Field["+fieldName+"] not in table.");
                                        } else {
                                            tiHash.add(fieldName);
                                        }
                                    }
                                } else if (cell instanceof FormCellFieldIFace) {
                                    FormCellFieldIFace fcf = (FormCellFieldIFace) cell;
                                    if (fcf.getUiType() == FormCellFieldIFace.FieldType.plugin) {
                                        String pluginName = fcf.getProperty("name");
                                        if (StringUtils.isNotEmpty(pluginName)) {
                                            checkPluginForNames(fcf, pluginName, tiHash);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    for (DBTableInfo ti : DBTableIdMgr.getInstance().getTables()) {
        int cnt = 0;

        HashSet<String> tiHash = viewFieldHash.get(ti.getName());
        if (tiHash != null) {
            tblTitle2Name.put(ti.getTitle(), ti.getName());

            //System.err.println(ti.getName() + " ----------------------");
            for (DBFieldInfo fi : ti.getFields()) {
                Boolean isInForm = tiHash.contains(fi.getName());
                modelList.add(
                        createRow(ti.getTitle(), fi.getName(), fi.getTitle(), isInForm, fi.isHidden(), cnt++));
            }

            for (DBRelationshipInfo ri : ti.getRelationships()) {
                Boolean isInForm = tiHash.contains(ri.getName());
                modelList.add(
                        createRow(ti.getTitle(), ri.getName(), ri.getTitle(), isInForm, ri.isHidden(), cnt++));
            }
        }
    }

    viewModel = new ViewModel();
    JTable table = new JTable(viewModel);

    sorter = new TableRowSorter<TableModel>(viewModel);
    searchTF = new JAutoCompTextField(20);

    table.setRowSorter(sorter);

    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,4px,f:p:g,2px,p:g"));
    SearchBox searchBox = new SearchBox(searchTF, null);

    filterCBX = UIHelper.createComboBox(new String[] { "None", "Not On Form, Not Hidden", "On Form, Hidden" });

    PanelBuilder searchPB = new PanelBuilder(new FormLayout("p,2px,p, f:p:g, p,2px,p", "p"));
    searchPB.add(UIHelper.createI18NFormLabel("SEARCH"), cc.xy(1, 1));
    searchPB.add(searchBox, cc.xy(3, 1));
    searchPB.add(UIHelper.createI18NFormLabel("Filter"), cc.xy(5, 1));
    searchPB.add(filterCBX, cc.xy(7, 1));

    JLabel legend = UIHelper.createLabel(
            "<HTML><li><font color=\"red\">Red</font> - Not on form and not hidden</li><li><font color=\"magenta\">Magenta</font> - On the form , but is hidden</li><li>Black - Correct</li>");
    legend.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
    PanelBuilder legPB = new PanelBuilder(new FormLayout("p,f:p:g", "p"));
    legPB.add(legend, cc.xy(1, 1));

    pb.add(searchPB.getPanel(), cc.xy(1, 1));
    pb.add(UIHelper.createScrollPane(table), cc.xy(1, 3));
    pb.add(legPB.getPanel(), cc.xy(1, 5));
    pb.setDefaultDialogBorder();

    sorter.setRowFilter(null);

    searchTF.getDocument().addDocumentListener(new DocumentAdaptor() {
        @Override
        protected void changed(DocumentEvent e) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    if (filterCBX.getSelectedIndex() > 0) {
                        blockCBXUpdate = true;
                        filterCBX.setSelectedIndex(-1);
                        blockCBXUpdate = false;
                    }
                    String text = searchTF.getText();
                    sorter.setRowFilter(text.isEmpty() ? null : RowFilter.regexFilter("^(?i)" + text, 0, 1));
                }
            });
        }
    });

    filterCBX.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (!blockCBXUpdate) {
                        RowFilter<TableModel, Integer> filter = null;
                        int inx = filterCBX.getSelectedIndex();
                        if (inx > 0) {
                            filter = filterCBX.getSelectedIndex() == 1 ? new NotOnFormNotHiddenRowFilter()
                                    : new OnFormIsHiddenRowFilter();
                        }
                        sorter.setRowFilter(filter);
                    }
                }
            });
        }
    });

    table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
    table.setDefaultRenderer(Boolean.class, new BiColorBooleanTableCellRenderer());
    table.getColumnModel().getColumn(0).setCellRenderer(new TitleCellFadeRenderer());
    table.getColumnModel().getColumn(3).setCellRenderer(new BiColorTableCellRenderer(true));
    table.getColumnModel().getColumn(2).setCellRenderer(new BiColorTableCellRenderer(false) {
        @SuppressWarnings("unchecked")
        @Override
        public Component getTableCellRendererComponent(JTable tableArg, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel lbl = (JLabel) super.getTableCellRendererComponent(tableArg, value, isSelected, hasFocus,
                    row, column);

            /*if (sorter.getRowFilter() != null)
            {
            System.out.println(" getRowCount:"+sorter.getModel().getRowCount());
            Pair<String, Integer> col1Pair = (Pair<String, Integer>)sorter.getModel().getValueAt(row, 0);
            rowData = modelList.get(col1Pair.second);
                    
            } else
            {
            rowData = modelList.get(row);
            }*/

            //System.out.println(" R2:"+row+"  "+rowData[0]+"/"+rowData[1]+" - "+rowData[3]+"|"+rowData[4]);
            if (value instanceof TableInfo) {
                TableInfo pair = (TableInfo) value;
                Object[] rowData = modelList.get(pair.getSecond());
                lbl.setText(rowData[0].toString());

            } else if (value instanceof Pair<?, ?>) {
                Pair<String, Integer> pair = (Pair<String, Integer>) value;
                Object[] rowData = modelList.get(pair.getSecond());

                boolean isOnForm = rowData[3] instanceof Boolean ? (Boolean) rowData[3]
                        : ((String) rowData[3]).equals("Yes");
                boolean isHidden = rowData[4] instanceof Boolean ? (Boolean) rowData[4]
                        : ((String) rowData[4]).equals("true");

                if (!isOnForm && !isHidden) {
                    lbl.setForeground(Color.RED);

                } else if (isOnForm && isHidden) {
                    lbl.setForeground(Color.MAGENTA);
                } else {
                    lbl.setForeground(Color.BLACK);
                }
                lbl.setText(pair.getFirst());
            } else {
                lbl.setText(value.toString());
            }
            return lbl;
        }

    });

    //UIHelper.makeTableHeadersCentered(table, false);
    UIHelper.calcColumnWidths(table, null);

    //Removing fix all button because fix() method is broken (bug #8087)...

    /*CustomDialog dlg = new CustomDialog((Frame)UIRegistry.getTopWindow(), "", true, CustomDialog.OKCANCELAPPLY, pb.getPanel()) 
    {
    @Override
    protected void applyButtonPressed()
    {
        fix(this);
    }
    };
    dlg.setApplyLabel("Fix All");*/

    CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(), "", true, CustomDialog.OKCANCEL,
            pb.getPanel());

    //... end removing fix all button

    dlg.setVisible(true);

    if (!dlg.isCancelled()) {
        updateSchema();
    }
}

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/*  w ww  .  j a v  a2  s .  c o  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;
}

From source file:es.emergya.ui.plugins.AdminPanel.java

/**
 * //from w  w w  .ja v  a2  s . c o m
 * @param columnNames
 *            nombres de las columnas de la tabla
 * @param filterOptions
 *            lista de opciones de un combobox. Si esta vacio entonces es un
 *            textfield
 * @param noFiltrarAction
 * @param filtrarAction
 */
public void generateTable(String[] columnNames, Object[][] filterOptions,
        AdminPanel.NoFiltrarAction noFiltrarAction, AdminPanel.FiltrarAction filtrarAction) {

    if (columnNames == null) {
        columnNames = new String[] {};
    }
    if (filterOptions == null) {
        filterOptions = new Object[][] {};
    }

    String filterString = "[";
    for (Object[] o : filterOptions) {
        filterString += Arrays.toString(o) + " ";
    }
    filterString += "]";

    log.debug("generateTable( columnNames = " + Arrays.toString(columnNames) + ", filterOptions = "
            + filterString + ")");

    tablePanel.removeAll();
    int columnNamesLength = columnNames.length;
    if (!getCanDelete())
        columnNamesLength++;
    MyTableModel dataModel = new MyTableModel(1, columnNamesLength + 2) {

        private static final long serialVersionUID = 1348355328684460769L;

        @Override
        public boolean isCellEditable(int row, int column) {
            return column != 0 && !invisibleFilterCols.contains(column);
        }
    };
    filters = new JTable(dataModel) {

        private static final long serialVersionUID = -8266991359840905405L;

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);

            if (isCellEditable(row, column) && column != getColumnCount() - 1) {
                if (c instanceof JTextField) {
                    ((JTextField) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                } else if (c instanceof JComboBox) {
                    ((JComboBox) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                } else if (c instanceof JLabel) {
                    ((JLabel) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                }
            }
            return c;
        }
    };
    filters.setSurrendersFocusOnKeystroke(true);
    filters.setShowGrid(false);
    filters.setRowHeight(22);
    filters.setOpaque(false);

    for (Integer i = 0; i < filterOptions.length; i++) {
        final Object[] items = filterOptions[i];
        if (items != null && items.length > 1) {
            setComboBoxEditor(i, items);
        } else {
            final DefaultCellEditor defaultCellEditor = new DefaultCellEditor(new JTextField());
            defaultCellEditor.setClickCountToStart(1);
            filters.getColumnModel().getColumn(i + 1).setCellEditor(defaultCellEditor);
        }
    }

    filters.setRowSelectionAllowed(false);
    filters.setDragEnabled(false);
    filters.setColumnSelectionAllowed(false);
    filters.setDefaultEditor(JButton.class, new JButtonCellEditor());

    filters.setDefaultRenderer(Object.class, new DefaultTableRenderer() {
        private static final long serialVersionUID = -4811729559786534118L;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (invisibleFilterCols.contains(column))
                c = new JLabel("");
            return c;
        }

    });

    filters.setDefaultRenderer(JButton.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JButton b = (JButton) value;
            b.setBorderPainted(false);
            b.setContentAreaFilled(false);
            return b;
        }
    });
    filters.setDefaultRenderer(JLabel.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            return (JLabel) value;
        }
    });
    filters.setDefaultEditor(JButton.class, new JButtonCellEditor());
    filters.getModel().setValueAt(new JLabel(""), 0, 0);
    JButton jButton2 = new JButton(noFiltrarAction);
    JButton jButton = new JButton(filtrarAction);
    jButton.setBorderPainted(false);
    jButton2.setBorderPainted(false);
    jButton.setContentAreaFilled(false);
    jButton2.setContentAreaFilled(false);
    if (jButton.getIcon() != null)
        jButton.setPreferredSize(
                new Dimension(jButton.getIcon().getIconWidth(), jButton.getIcon().getIconHeight()));
    if (jButton2.getIcon() != null)
        jButton2.setPreferredSize(
                new Dimension(jButton2.getIcon().getIconWidth(), jButton2.getIcon().getIconHeight()));

    filters.getModel().setValueAt(jButton, 0, columnNamesLength - 1);
    filters.getColumnModel().getColumn(columnNamesLength - 1).setMinWidth(jButton.getWidth() + 24);
    filters.getModel().setValueAt(jButton2, 0, columnNamesLength);
    filters.getColumnModel().getColumn(columnNamesLength).setMinWidth(jButton2.getWidth() + 14);
    cuenta.setHorizontalAlignment(JLabel.CENTER);
    cuenta.setText("?/?");
    filters.getModel().setValueAt(cuenta, 0, columnNamesLength + 1);

    tablePanel.add(filters, BorderLayout.NORTH);

    Vector<String> headers = new Vector<String>();
    headers.add("");
    headers.addAll(Arrays.asList(columnNames));
    MyTableModel model = new MyTableModel(headers, 0);
    table = new JTable(model) {

        private static final long serialVersionUID = 949284378605881770L;
        private int highLightedRow = -1;
        private Rectangle dirtyRegion = null;

        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            try {
                if (AdminPanel.this.myRendererColoring != null)
                    c.setBackground(AdminPanel.this.myRendererColoring
                            .getColor(AdminPanel.this.table.getValueAt(row, 1)));
            } catch (Throwable t) {
                log.error("Error al colorear la celda: " + t);
            }
            return c;
        }

        @Override
        protected void processMouseMotionEvent(MouseEvent e) {
            try {
                int row = rowAtPoint(e.getPoint());
                Graphics g = getGraphics();
                if (row == -1) {
                    highLightedRow = -1;
                }

                // row changed
                if (highLightedRow != row) {
                    if (null != dirtyRegion) {
                        paintImmediately(dirtyRegion);
                    }
                    for (int j = 0; j < getRowCount(); j++) {
                        if (row == j) {
                            // highlight
                            Rectangle firstRowRect = getCellRect(row, 0, false);
                            Rectangle lastRowRect = getCellRect(row, getColumnCount() - 1, false);
                            dirtyRegion = firstRowRect.union(lastRowRect);
                            g.setColor(new Color(0xff, 0xff, 0, 100));
                            g.fillRect((int) dirtyRegion.getX(), (int) dirtyRegion.getY(),
                                    (int) dirtyRegion.getWidth(), (int) dirtyRegion.getHeight());
                            highLightedRow = row;
                        }

                    }
                }
            } catch (Exception ex) {
            }
            super.processMouseMotionEvent(e);
        }
    };

    table.setRowHeight(22);

    table.setOpaque(false);
    // table.setAutoCreateRowSorter(true);

    table.setDragEnabled(false);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);

    table.setDefaultEditor(JButton.class, new JButtonCellEditor());
    table.setDefaultRenderer(JButton.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JButton b = (JButton) value;
            if (b != null) {
                b.setBorderPainted(false);
                b.setContentAreaFilled(false);
            }
            return b;
        }
    });

    JScrollPane jScrollPane = new JScrollPane(table);
    jScrollPane.setOpaque(false);
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane.getViewport().setOpaque(false);
    tablePanel.add(jScrollPane, BorderLayout.CENTER);
}

From source file:org.drugis.addis.gui.components.EnhancedTable.java

public static void insertEntityRenderer(JTable table) {
    final TableCellRenderer defaultRenderer = table.getDefaultRenderer(Object.class);
    EntityRenderer renderer = new EntityRenderer(defaultRenderer);
    table.setDefaultRenderer(Object.class, renderer);
    // Entity is an interface, and if something returns a sub-interface of Entity, that is not a sub-type of Object
    // Hence, we have to attach the renderer to Entity.class as well.
    table.setDefaultRenderer(Entity.class, renderer);
}