Example usage for javax.swing JTable addMouseListener

List of usage examples for javax.swing JTable addMouseListener

Introduction

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

Prototype

public synchronized void addMouseListener(MouseListener l) 

Source Link

Document

Adds the specified mouse listener to receive mouse events from this component.

Usage

From source file:SimpleTableSelectionDemo.java

public SimpleTableSelectionDemo() {
    super(new GridLayout(1, 0));

    final String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };

    final Object[][] data = { { "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false) },
            { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
            { "Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false) },
            { "Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true) },
            { "Philip", "Milne", "Pool", new Integer(10), new Boolean(false) } };

    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);/*from   w  w  w.  j  av a  2  s  . c  o  m*/

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    if (ALLOW_ROW_SELECTION) { // true by default
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                // Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No rows are selected.");
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.out.println("Row " + selectedRow + " is now selected.");
                }
            }
        });
    } else {
        table.setRowSelectionAllowed(false);
    }

    if (ALLOW_COLUMN_SELECTION) { // false by default
        if (ALLOW_ROW_SELECTION) {
            // We allow both row and column selection, which
            // implies that we *really* want to allow individual
            // cell selection.
            table.setCellSelectionEnabled(true);
        }
        table.setColumnSelectionAllowed(true);
        ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
        colSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                // Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No columns are selected.");
                } else {
                    int selectedCol = lsm.getMinSelectionIndex();
                    System.out.println("Column " + selectedCol + " is now selected.");
                }
            }
        });
    }

    if (DEBUG) {
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                printDebugData(table);
            }
        });
    }

    // Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    // Add the scroll pane to this panel.
    add(scrollPane);
}

From source file:com.intuit.tank.proxy.ProxyApp.java

private JPanel getTransactionTable() {
    JPanel frame = new JPanel(new BorderLayout());
    model = new TransactionTableModel();
    final JTable table = new TransactionTable(model);
    final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);// ww  w  .ja  v a  2 s . co  m
    final JPopupMenu pm = new JPopupMenu();
    JMenuItem item = new JMenuItem("Delete Selected");
    item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int[] selectedRows = table.getSelectedRows();
            if (selectedRows.length != 0) {
                int response = JOptionPane.showConfirmDialog(ProxyApp.this,
                        "Are you sure you want to delete " + selectedRows.length + " Transactions?",
                        "Confirm Delete", JOptionPane.YES_NO_OPTION);
                if (response == JOptionPane.YES_OPTION) {
                    int[] correctedRows = new int[selectedRows.length];
                    for (int i = selectedRows.length; --i >= 0;) {
                        int row = selectedRows[i];
                        int index = (Integer) table.getValueAt(row, 0) - 1;
                        correctedRows[i] = index;
                    }
                    Arrays.sort(correctedRows);
                    for (int i = correctedRows.length; --i >= 0;) {
                        int row = correctedRows[i];
                        Transaction transaction = model.getTransactionForIndex(row);
                        if (transaction != null) {
                            model.removeTransaction(transaction, row);
                            isDirty = true;
                            saveAction.setEnabled(isDirty && !stopAction.isEnabled());
                        }
                    }
                }
            }
        }
    });
    pm.add(item);
    table.add(pm);

    table.addMouseListener(new MouseAdapter() {
        boolean pressed = false;

        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                Point p = e.getPoint();
                int row = table.rowAtPoint(p);
                int index = (Integer) table.getValueAt(row, 0) - 1;
                Transaction transaction = model.getTransactionForIndex(index);
                if (transaction != null) {
                    detailsTF.setText(transaction.toString());
                    detailsTF.setCaretPosition(0);
                    detailsDialog.setVisible(true);
                }
            }
        }

        /**
         * @{inheritDoc
         */
        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                pressed = true;
                int[] selectedRows = table.getSelectedRows();
                if (selectedRows.length != 0) {
                    pm.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }

        /**
         * @{inheritDoc
         */
        @Override
        public void mouseReleased(MouseEvent e) {
            if (!pressed && e.isPopupTrigger()) {
                int[] selectedRows = table.getSelectedRows();
                if (selectedRows.length != 0) {
                    pm.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }

    });

    JScrollPane pane = new JScrollPane(table);
    frame.add(pane, BorderLayout.CENTER);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Filter: ");
    panel.add(label, BorderLayout.WEST);
    final JLabel countLabel = new JLabel(" Count: 0 ");
    panel.add(countLabel, BorderLayout.EAST);
    final JTextField filterText = new JTextField("");
    filterText.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
            String text = filterText.getText();
            if (text.length() == 0) {
                sorter.setRowFilter(null);
            } else {
                try {
                    sorter.setRowFilter(RowFilter.regexFilter(text));
                    countLabel.setText(" Count: " + sorter.getViewRowCount() + " ");
                } catch (PatternSyntaxException pse) {
                    System.err.println("Bad regex pattern");
                }
            }
        }
    });
    panel.add(filterText, BorderLayout.CENTER);

    frame.add(panel, BorderLayout.NORTH);
    return frame;
}

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

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

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

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

                return true;
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                TableCellEditor tce = table.getCellEditor();

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

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

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

    p.add(scrollpane, BorderLayout.CENTER);

    detailsTableModel.fireTableStructureChanged();

    return p;
}

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

private JPanel createStatPanel(Stx stx, final Mask regionalMask, final Mask qualityMask, int stxIdx,
        RasterDataNode raster) {// ww  w.  jav a2  s.  c o 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:interfaces.InterfazPrincipal.java

private void botonBuscarClienteCrearFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarClienteCrearFacturaActionPerformed

    String nombre = nombreClienteCrearFactura.getText();
    String identificacion = IdentificacionClienteBuscarFactura.getText();

    ControladorCliente controladorCliente = new ControladorCliente();

    try {//from   w w w . j  a  v a 2s. c o m
        int id = 0;
        if (!identificacion.equals("")) {
            id = Integer.parseInt(identificacion);
        }

        ArrayList<Cliente> listaClientes = controladorCliente.obtenerClientes(nombre, id);

        if (listaClientes.isEmpty()) {
            mensajesBusquedaClientesFactura.setText("La busqueda no arrojo resultados");
            return;
        }

        final JDialog dialogoEditar = new JDialog(this);
        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(600, 310);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;

        JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 4;
        c.insets = new Insets(15, 200, 40, 0);
        c.ipadx = 100;
        Font textoGrande = new Font("Arial", 1, 18);
        editarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(editarTextoPrincipalDialogo, c);

        /*Vector col = new Vector();
         col.add("1");
         col.add("2");
         col.add("3");
         col.add("4");
         Vector row = new Vector();
                
         for (int i = 0; i < listaClientes.size(); i++) {
         Cliente cliente = listaClientes.get(i);
         Vector temp = new Vector();
         temp.add((i + 1) + "");
         temp.add(cliente.getNombre());
         temp.add(cliente.getCliente_id() + "");
         temp.add(cliente.getMonto_prestamo() + "");
         System.out.println("info" + cliente.getNombre() + "," + cliente.getMonto_prestamo());
         row.add(temp);
         }
                
         final JTable table = new JTable(row, col);         */
        final JTable table = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

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

        modeloTabla.addColumn("Numero");
        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");
        modeloTabla.addColumn("Monto Prestamo");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2", "3", "4" };
            data[0] = (i + 1);
            data[1] = listaClientes.get(i).getCliente_id();
            data[2] = listaClientes.get(i).getNombre();
            data[3] = listaClientes.get(i).getMonto_prestamo();

            modeloTabla.addRow(data);
        }

        table.setModel(modeloTabla);
        table.getColumn("Numero").setMinWidth(50);
        table.getColumn("Identificacin").setMinWidth(50);
        table.getColumn("Nombre").setMinWidth(110);
        table.getColumn("Monto Prestamo").setMinWidth(110);

        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setPreferredSize(new Dimension(320, 150));

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                String identificacion = table.getValueAt(table.getSelectedRow(), 3).toString();
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                        " where factura_id in (select factura_id from Factura where cliente_id = "
                                + String.valueOf(identificacion)
                                + " and estado=\"fiado\") order by factura_id");
                double pago = 0.0;

                for (int i = 0; i < flujosCliente.size(); i++) {
                    String[] datos = flujosCliente.get(i);
                    Object[] rowData = { datos[1], datos[2], datos[3], datos[4] };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                }
                nombreClienteCrearFactura.setText(table.getValueAt(table.getSelectedRow(), 2).toString());
                IdentificacionClienteBuscarFactura
                        .setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                double montoPrestamo = Double
                        .parseDouble(table.getValueAt(table.getSelectedRow(), 3).toString());
                Double totalDisponible = montoPrestamo - pago;
                valorActualPrestamo.setText(String.valueOf(totalDisponible));
                //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
                botonAgregarProducto.setEnabled(true);
                botonGuardarFactura.setEnabled(true);
                botonEstablecerMontoFactura.setEnabled(true);
                dialogoEditar.dispose();
            }
        });

        c.insets = new Insets(0, 5, 10, 0);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 1;
        c.ipadx = 200;

        //panelDialogo.add(table, c);
        panelDialogo.add(scroll, c);
        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);
    } catch (Exception e) {
        mensajesBusquedaClientesFactura.setText("La identificacion debe ser un numero");

    }

}

From source file:interfaces.InterfazPrincipal.java

private void botonAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarProductoActionPerformed
    String nombre = jTextField_Factura_Producto_Nombre.getText();
    String descripcion = jTextField_Factura_Producto_Descripcion.getText();
    ControladorProducto controladorPro = new ControladorProducto();
    String restriccion = "";

    boolean encounter = true;

    if (!nombre.equals("")) {
        if (encounter) {
            encounter = false;//from   www  .  j  a v  a2 s .  c  o  m
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " nombre like '%" + nombre + "%'";
    }

    if (!descripcion.equals("")) {
        if (encounter) {
            encounter = false;
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " descripcion like '%" + descripcion + "%'";
    }

    ArrayList<Productos> listaDeProductos = controladorPro.getProducto(restriccion);

    final JDialog dialogoEditar = new JDialog(this);
    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(600, 310);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Producto");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 6;
    c.insets = new Insets(15, 200, 40, 0);
    c.ipadx = 100;
    Font textoGrande = new Font("Arial", 1, 18);
    editarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(editarTextoPrincipalDialogo, c);

    final JTable table = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

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

    modeloTabla.addColumn("Numero");
    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");
    modeloTabla.addColumn("Descripcion");
    modeloTabla.addColumn("Unidades Disponibles");
    modeloTabla.addColumn("Precio");

    //LLenar tabla
    for (int i = 0; i < listaDeProductos.size(); i++) {
        Object[] data = { "1", "2", "3", "4", "5", "6" };
        data[0] = (i + 1);
        data[1] = listaDeProductos.get(i).getProductoId();
        data[2] = listaDeProductos.get(i).getNombre();
        data[3] = listaDeProductos.get(i).getDescripcion();
        data[4] = listaDeProductos.get(i).getUnidadesDisponibles();
        data[5] = listaDeProductos.get(i).getPrecio();

        modeloTabla.addRow(data);
    }

    table.setModel(modeloTabla);
    table.getColumn("Numero").setMinWidth(50);
    table.getColumn("Identificacin").setMinWidth(50);
    table.getColumn("Nombre").setMinWidth(110);
    table.getColumn("Descripcion").setMinWidth(110);
    table.getColumn("Unidades Disponibles").setMinWidth(40);
    table.getColumn("Precio").setMinWidth(110);

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize(new Dimension(320, 150));

    //final JTable table = new JTable(row, col);       
    table.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            //jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
            //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
            DefaultTableModel modelo = (DefaultTableModel) TablaDeFacturaProducto.getModel();

            Object[] fila = new Object[7];

            fila[0] = table.getValueAt(table.getSelectedRow(), 0).toString();
            fila[1] = table.getValueAt(table.getSelectedRow(), 1).toString();
            fila[2] = table.getValueAt(table.getSelectedRow(), 2).toString();
            fila[3] = table.getValueAt(table.getSelectedRow(), 3).toString();
            //fila[4] = table.getValueAt(table.getSelectedRow(), 4).toString();
            fila[4] = (String) JOptionPane.showInputDialog("Ingrese el nmero de unidades que va a vender");
            fila[5] = table.getValueAt(table.getSelectedRow(), 5).toString();

            Double valorProducto = Double.parseDouble((String) fila[5]);
            String valorActualProducto = String.valueOf(Double.parseDouble(valorActualFactura.getText())
                    + Double.parseDouble((String) fila[4]) * valorProducto);
            valorActualFactura.setText(valorActualProducto);
            fila[6] = Double.parseDouble((String) fila[4]) * valorProducto;
            modelo.addRow(fila);
            //modelo.getColumnName(4).
            /*TablaDeFacturaProducto.setModel(modelo);
             TablaDeFacturaProducto.getColumnClass(4). ;*/
            dialogoEditar.dispose();
        }
    });

    c.insets = new Insets(0, 5, 10, 0);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 200;

    panelDialogo.add(scroll, c);

    //panelDialogo.add(table, c);
    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

}

From source file:nl.detoren.ijsco.ui.Mainscreen.java

public JPanel createDeelnemersPanel() {
    JPanel panel = new JPanel(false);
    panel.setBackground(Color.BLACK);
    //panel.setLayout(new GridLayout(1, 0));
    panel.setLayout(new BorderLayout());
    JPanel innerPanel = new JPanel();
    JLabel lbAanwezig = new JLabel("Deelnemers: ");
    innerPanel.add(lbAanwezig, BorderLayout.NORTH);
    tfAanwezig = new JLabel(Integer.toString(status.deelnemers.aantalAanwezig()), 10);
    innerPanel.add(tfAanwezig, BorderLayout.NORTH);
    //innerPanel.setLayout(new GridLayout(1, 0));
    innerPanel.add(new JLabel("Naam:"), BorderLayout.NORTH);
    JTextField deelnemer = new JTextField(15);
    ArrayList<String> words = new ArrayList<>();
    if (status.OSBOSpelers != null) {
        for (Speler s : status.OSBOSpelers.values()) {
            words.add(s.getNaam().trim());
            words.add(Integer.toString(s.getKnsbnummer()));
        }//from   ww w. j a  v  a 2  s .co m
    }
    @SuppressWarnings("unused")
    Suggesties suggesties = new Suggesties(deelnemer, this, words, 2);
    innerPanel.add(deelnemer, BorderLayout.NORTH);
    deelnemer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            actieVoegSpelerToe(deelnemer.getText().trim());
            deelnemer.setText("");
        }
    });

    JButton btVoegToe = new JButton("Voeg toe");
    btVoegToe.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            actieVoegSpelerToe(deelnemer.getText().trim());
            deelnemer.setText("");
        }
    });
    innerPanel.add(btVoegToe);
    panel.add(innerPanel);
    // panel_deelnemers.add(new JLabel("Deelnemers IJSCO toernooi"));
    deelnemersModel = new DeelnemersModel(panel, status.deelnemers);
    JTable deelnemersTabel = new JTable(deelnemersModel) {
        private static final long serialVersionUID = -8293073016982337108L;

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            DeelnemersModel model = (DeelnemersModel) getModel();
            // Tooltip
            if (c instanceof JComponent) {
                ((JComponent) c)
                        .setToolTipText(model.getToolTip(convertRowIndexToModel(row), column).toString());
            }

            // Alternate row color
            if (!isRowSelected(row)) {
                c.setBackground(row % 2 == 0 ? Color.WHITE : Color.LIGHT_GRAY);
            }

            // Highlight overruled entries
            if (status.deelnemers.get(convertRowIndexToModel(row)).isOverruleNaam()
                    || status.deelnemers.get(convertRowIndexToModel(row)).isOverruleNaam()) {
                c.setForeground(Color.BLUE);
            } else {
                c.setForeground(Color.BLACK);
            }
            return c;
        }
    };

    deelnemersTabel.getModel().addTableModelListener(new TableModelListener() {

        @Override
        public void tableChanged(TableModelEvent arg0) {
            status.groepen = null;
            status.schemas = null;
            status.schema = null;
            groepenText.setText("");
            schemaModel.setSchemas(null);
            schemaModel.fireTableDataChanged();
            if (status.deelnemers != null && tfAanwezig != null) {
                tfAanwezig.setText(Integer.toString(status.deelnemers.aantalAanwezig()));
            }
            panel.repaint();
        }

    });

    deelnemersTabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            logger.log(Level.INFO, "MouseEvent on table fired, type : " + e.toString());
            logger.log(Level.INFO, "Popup trigger? : " + e.isPopupTrigger());
            if (e.isPopupTrigger()) {
                int row = deelnemersTabel.rowAtPoint(e.getPoint());
                JPopupMenu popup = new JPopupMenu();
                JMenuItem menuItem = new JMenuItem("Bewerk speler");
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        logger.log(Level.INFO,
                                "Bewerk Speler  : " + deelnemersTabel.convertRowIndexToModel(row));
                        Speler s = status.deelnemers.get(deelnemersTabel.convertRowIndexToModel(row));
                        BewerkSpelerDialoog rd = new BewerkSpelerDialoog(new JFrame(), "Bewerk Speler", s,
                                deelnemersModel);
                        rd.addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosed(WindowEvent e) {
                                System.out.println("closing...");
                            }

                        });
                        rd.setVisible(true);
                    }

                });
                popup.add(menuItem);

                menuItem = new JMenuItem("Verwijder Speler");
                popup.add(menuItem);
                menuItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        logger.log(Level.INFO,
                                "Verwijder Speler  : " + deelnemersTabel.convertRowIndexToModel(row));
                        Speler s = status.deelnemers.get(deelnemersTabel.convertRowIndexToModel(row));
                        status.deelnemers.remove(s);
                        deelnemersModel.fireTableDataChanged();
                    }
                });
                popup.show(e.getComponent(), e.getX(), e.getY());

            }
        }
    });

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(deelnemersTabel);
    innerPanel.add(scrollPane, BorderLayout.CENTER);

    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(deelnemersModel);
    deelnemersTabel.setRowSorter(sorter);

    innerPanel.add(new JLabel("Filter op : "));
    JTextField tfFilter = new JTextField(10);
    tfFilter.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            String text = tfFilter.getText();
            logger.log(Level.INFO, "Filter tabel op : " + text);
            if (text.length() == 0) {
                sorter.setRowFilter(null);
            } else {
                sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
        }
    });
    innerPanel.add(tfFilter);
    JButton btPasToe = new JButton("Apply");
    btPasToe.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            String text = tfFilter.getText();
            logger.log(Level.INFO, "Filter tabel op : " + text);
            if (text.length() == 0) {
                sorter.setRowFilter(null);
            } else {
                sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
        }
    });
    innerPanel.add(btPasToe);
    JButton btWis = new JButton("Wis");
    btWis.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            tfFilter.setText("");
            logger.log(Level.INFO, "Wis filter");
            sorter.setRowFilter(null);
        }
    });
    innerPanel.add(btWis);

    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(0), 30);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(1), 55);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(2), 170);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(3), 40);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(4), 40);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(5), 30);
    Utils.fixedComponentSize(scrollPane, 400, 580);
    return panel;
}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java

private JTable createTable(final ViewState state) {
    JTable table;
    final ModelGraph selected = state.getSelected();
    if (selected != null) {
        final Vector<Vector<String>> rows = new Vector<Vector<String>>();
        ConcurrentHashMap<String, String> keyToGroupMap = new ConcurrentHashMap<String, String>();
        Metadata staticMet = selected.getModel().getStaticMetadata();
        Metadata inheritedMet = selected.getInheritedStaticMetadata(state);
        Metadata completeMet = new Metadata();
        if (staticMet != null) {
            completeMet.replaceMetadata(staticMet.getSubMetadata(state.getCurrentMetGroup()));
        }//  w ww.j  a  v  a  2  s  .c  o  m
        if (selected.getModel().getExtendsConfig() != null) {
            for (String configGroup : selected.getModel().getExtendsConfig()) {
                Metadata extendsMetadata = state.getGlobalConfigGroups().get(configGroup).getMetadata()
                        .getSubMetadata(state.getCurrentMetGroup());
                for (String key : extendsMetadata.getAllKeys()) {
                    if (!completeMet.containsKey(key)) {
                        keyToGroupMap.put(key, configGroup);
                        completeMet.replaceMetadata(key, extendsMetadata.getAllMetadata(key));
                    }
                }
            }
        }
        if (inheritedMet != null) {
            Metadata inheritedMetadata = inheritedMet.getSubMetadata(state.getCurrentMetGroup());
            for (String key : inheritedMetadata.getAllKeys()) {
                if (!completeMet.containsKey(key)) {
                    keyToGroupMap.put(key, "__inherited__");
                    completeMet.replaceMetadata(key, inheritedMetadata.getAllMetadata(key));
                }
            }
        }
        List<String> keys = completeMet.getAllKeys();
        Collections.sort(keys);
        for (String key : keys) {
            if (key.endsWith("/envReplace")) {
                continue;
            }
            String values = StringUtils.join(completeMet.getAllMetadata(key), ",");
            Vector<String> row = new Vector<String>();
            row.add(keyToGroupMap.get(key));
            row.add(key);
            row.add(values);
            row.add(Boolean.toString(Boolean.parseBoolean(completeMet.getMetadata(key + "/envReplace"))));
            rows.add(row);
        }
        table = new JTable();// rows, new Vector<String>(Arrays.asList(new
                             // String[] { "key", "values", "envReplace" })));
        table.setModel(new AbstractTableModel() {
            public String getColumnName(int col) {
                switch (col) {
                case 0:
                    return "group";
                case 1:
                    return "key";
                case 2:
                    return "values";
                case 3:
                    return "envReplace";
                default:
                    return null;
                }
            }

            public int getRowCount() {
                return rows.size() + 1;
            }

            public int getColumnCount() {
                return 4;
            }

            public Object getValueAt(int row, int col) {
                if (row >= rows.size()) {
                    return null;
                }
                String value = rows.get(row).get(col);
                if (value == null && col == 3) {
                    return "false";
                }
                if (value == null && col == 0) {
                    return "__local__";
                }
                return value;
            }

            public boolean isCellEditable(int row, int col) {
                if (row >= rows.size()) {
                    return selected.getModel().getStaticMetadata().containsGroup(state.getCurrentMetGroup());
                }
                if (col == 0) {
                    return false;
                }
                String key = rows.get(row).get(1);
                return key == null || (selected.getModel().getStaticMetadata() != null
                        && selected.getModel().getStaticMetadata().containsKey(getKey(key, state)));
            }

            public void setValueAt(Object value, int row, int col) {
                if (row >= rows.size()) {
                    Vector<String> newRow = new Vector<String>(
                            Arrays.asList(new String[] { null, null, null, null }));
                    newRow.add(col, (String) value);
                    rows.add(newRow);
                } else {
                    Vector<String> rowValues = rows.get(row);
                    rowValues.add(col, (String) value);
                    rowValues.remove(col + 1);
                }
                this.fireTableCellUpdated(row, col);
            }

        });
        MyTableListener tableListener = new MyTableListener(state);
        table.getModel().addTableModelListener(tableListener);
        table.getSelectionModel().addListSelectionListener(tableListener);
    } else {
        table = new JTable(new Vector<Vector<String>>(),
                new Vector<String>(Arrays.asList(new String[] { "key", "values", "envReplace" })));
    }

    // table.setFillsViewportHeight(true);
    table.setSelectionBackground(Color.cyan);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    TableCellRenderer cellRenderer = new TableCellRenderer() {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel field = new JLabel((String) value);
            if (column == 0) {
                field.setForeground(Color.gray);
            } else {
                if (isSelected) {
                    field.setBorder(new EtchedBorder(1));
                }
                if (table.isCellEditable(row, 1)) {
                    field.setForeground(Color.black);
                } else {
                    field.setForeground(Color.gray);
                }
            }
            return field;
        }

    };
    TableColumn groupCol = table.getColumnModel().getColumn(0);
    groupCol.setPreferredWidth(75);
    groupCol.setCellRenderer(cellRenderer);
    TableColumn keyCol = table.getColumnModel().getColumn(1);
    keyCol.setPreferredWidth(200);
    keyCol.setCellRenderer(cellRenderer);
    TableColumn valuesCol = table.getColumnModel().getColumn(2);
    valuesCol.setPreferredWidth(300);
    valuesCol.setCellRenderer(cellRenderer);
    TableColumn envReplaceCol = table.getColumnModel().getColumn(3);
    envReplaceCol.setPreferredWidth(75);
    envReplaceCol.setCellRenderer(cellRenderer);

    table.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3 && DefaultPropView.this.table.getSelectedRow() != -1) {
                int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition());
                String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state);
                Metadata staticMet = state.getSelected().getModel().getStaticMetadata();
                override.setVisible(staticMet == null || !staticMet.containsKey(key));
                delete.setVisible(staticMet != null && staticMet.containsKey(key));
                tableMenu.show(DefaultPropView.this.table, e.getX(), e.getY());
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });

    return table;
}

From source file:org.formic.wizard.step.gui.FeatureListStep.java

/**
 * {@inheritDoc}//from   w  w w  . ja va 2s  .  com
 * @see org.formic.wizard.step.GuiStep#init()
 */
public Component init() {
    featureInfo = new JEditorPane("text/html", StringUtils.EMPTY);
    featureInfo.setEditable(false);
    featureInfo.addHyperlinkListener(new HyperlinkListener());

    Feature[] features = provider.getFeatures();
    JTable table = new JTable(features.length, 1) {
        private static final long serialVersionUID = 1L;

        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    table.setBackground(new javax.swing.JList().getBackground());

    GuiForm form = createForm();

    for (int ii = 0; ii < features.length; ii++) {
        final Feature feature = (Feature) features[ii];
        final JCheckBox box = new JCheckBox();

        String name = getName() + '.' + feature.getKey();
        form.bind(name, box);

        box.putClientProperty("feature", feature);
        featureMap.put(feature.getKey(), box);

        if (feature.getInfo() == null) {
            feature.setInfo(Installer.getString(getName() + "." + feature.getKey() + ".html"));
        }
        feature.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                if (Feature.ENABLED_PROPERTY.equals(event.getPropertyName())) {
                    if (box.isSelected() != feature.isEnabled()) {
                        box.setSelected(feature.isEnabled());
                    }
                }
            }
        });

        box.setText(Installer.getString(name));
        box.setBackground(table.getBackground());
        if (!feature.isAvailable()) {
            box.setSelected(false);
            box.setEnabled(false);
        }
        table.setValueAt(box, ii, 0);
    }

    FeatureListMouseListener mouseListener = new FeatureListMouseListener();
    for (int ii = 0; ii < features.length; ii++) {
        Feature feature = (Feature) features[ii];
        if (feature.isEnabled() && feature.isAvailable()) {
            JCheckBox box = (JCheckBox) featureMap.get(feature.getKey());
            box.setSelected(true);
            mouseListener.processDependencies(feature);
            mouseListener.processExclusives(feature);
        }
    }

    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowHorizontalLines(false);
    table.setShowVerticalLines(false);
    table.setDefaultRenderer(JCheckBox.class, new ComponentTableCellRenderer());

    table.addKeyListener(new FeatureListKeyListener());
    table.addMouseListener(mouseListener);
    table.getSelectionModel().addListSelectionListener(new FeatureListSelectionListener(table));

    table.setRowSelectionInterval(0, 0);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    JPanel container = new JPanel(new BorderLayout());
    container.add(table, BorderLayout.CENTER);
    panel.add(new JScrollPane(container), BorderLayout.CENTER);
    JScrollPane infoScroll = new JScrollPane(featureInfo);
    infoScroll.setMinimumSize(new Dimension(0, 50));
    infoScroll.setMaximumSize(new Dimension(0, 50));
    infoScroll.setPreferredSize(new Dimension(0, 50));
    panel.add(infoScroll, BorderLayout.SOUTH);

    return panel;
}

From source file:org.isatools.isacreator.spreadsheet.Spreadsheet.java

/**
 * Setup the JTable with its desired characteristics
 *//*from  w  ww.jav  a  2s.  c  om*/
private void setupTable() {
    table = new CustomTable(spreadsheetModel);
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);
    table.setShowVerticalLines(true);
    table.setShowHorizontalLines(true);
    table.setGridColor(UIHelper.LIGHT_GREEN_COLOR);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    table.setAutoCreateColumnsFromModel(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.getSelectionModel().addListSelectionListener(this);
    table.getColumnModel().getSelectionModel().addListSelectionListener(this);
    table.getTableHeader().setReorderingAllowed(true);
    table.getColumnModel().addColumnModelListener(this);
    try {
        table.setDefaultRenderer(Class.forName("java.lang.Object"), new SpreadsheetCellRenderer());
    } catch (ClassNotFoundException e) {
        // ignore this error
    }

    table.addMouseListener(this);
    table.getTableHeader().addMouseMotionListener(new MouseMotionListener() {
        public void mouseDragged(MouseEvent event) {
        }

        public void mouseMoved(MouseEvent event) {
            // display a tooltip when user hovers over a column. tooltip is derived
            // from the description of a field from the TableReferenceObject.
            JTable table = ((JTableHeader) event.getSource()).getTable();
            TableColumnModel colModel = table.getColumnModel();
            int colIndex = colModel.getColumnIndexAtX(event.getX());

            // greater than 1 to account for the row no. being the first col
            if (colIndex >= 1) {
                TableColumn tc = colModel.getColumn(colIndex);
                if (tc != null) {
                    try {
                        table.getTableHeader().setToolTipText(getFieldDescription(tc));
                    } catch (Exception e) {
                        // ignore this error
                    }
                }
            }
        }
    });

    //table.getColumnModel().addColumnModelListener(this);
    InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);

    //  Override the default tab behaviour
    //  Tab to the next editable cell. When no editable cells goto next cell.
    final Action previousTabAction = table.getActionMap().get(im.get(tab));
    Action newTabAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            // maintain previous tab action procedure
            previousTabAction.actionPerformed(e);

            JTable table = (JTable) e.getSource();
            int row = table.getSelectedRow();
            int originalRow = row;
            int column = table.getSelectedColumn();
            int originalColumn = column;

            while (!table.isCellEditable(row, column)) {
                previousTabAction.actionPerformed(e);
                row = table.getSelectedRow();
                column = table.getSelectedColumn();

                //  Back to where we started, get out.
                if ((row == originalRow) && (column == originalColumn)) {
                    break;
                }
            }

            if (table.editCellAt(row, column)) {
                table.getEditorComponent().requestFocusInWindow();
            }
        }
    };

    table.getActionMap().put(im.get(tab), newTabAction);
    TableColumnModel model = table.getColumnModel();

    String previousColumnName = null;
    for (int columnIndex = 0; columnIndex < tableReferenceObject.getHeaders().size(); columnIndex++) {
        if (!model.getColumn(columnIndex).getHeaderValue().toString()
                .equals(TableReferenceObject.ROW_NO_TEXT)) {
            model.getColumn(columnIndex).setHeaderRenderer(columnRenderer);
            model.getColumn(columnIndex).setPreferredWidth(spreadsheetFunctions
                    .calcColWidths(model.getColumn(columnIndex).getHeaderValue().toString()));
            // add appropriate cell editor for cell.
            spreadsheetFunctions.addCellEditor(model.getColumn(columnIndex), previousColumnName);
            previousColumnName = model.getColumn(columnIndex).getHeaderValue().toString();
        } else {
            model.getColumn(columnIndex).setHeaderRenderer(new RowNumberCellRenderer());
        }
    }

    JTableHeader header = table.getTableHeader();
    header.setBackground(UIHelper.BG_COLOR);
    header.addMouseListener(new HeaderListener(header, columnRenderer));

    table.addNotify();
}