List of usage examples for javax.swing JTable getColumn
public TableColumn getColumn(Object identifier)
TableColumn
object for the column in the table whose identifier is equal to identifier
, when compared using equals
. From source file:interfaces.InterfazPrincipal.java
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed // TODO add your handling code here: String nombre = jTextFieldNombreSaldoProveedores.getText(); ControladorProveedores controladorProveedores = new ControladorProveedores(); ArrayList<Proveedores> listaProveedores = controladorProveedores.obtenerProveedores("", nombre); final JDialog dialogoEditar = new JDialog(this); dialogoEditar.setTitle("Buscar proveedores"); dialogoEditar.setSize(500, 300);/* w ww . j av a 2 s . co m*/ dialogoEditar.setResizable(false); JPanel panelDialogo = new JPanel(); panelDialogo.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar Proveedores"); c.gridx = 0; c.gridy = 0; c.gridwidth = 3; c.insets = new Insets(10, 60, 10, 10); Font textoGrande = new Font("Arial", 1, 16); ediitarTextoPrincipalDialogo.setFont(textoGrande); panelDialogo.add(ediitarTextoPrincipalDialogo, c); c.gridx = 0; c.gridy = 1; c.gridwidth = 3; c.insets = new Insets(10, 10, 10, 10); final JTable tablaDialogo = new JTable(); DefaultTableModel modeloTabla = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { //all cells false return false; } }; ; modeloTabla.addColumn("ID"); modeloTabla.addColumn("Identificacin"); modeloTabla.addColumn("Nombre"); //LLenar tabla for (int i = 0; i < listaProveedores.size(); i++) { Object[] data = { "1", "2", "3" }; data[0] = listaProveedores.get(i).getID(); data[1] = listaProveedores.get(i).getIdentificacion(); data[2] = listaProveedores.get(i).getNombre(); System.out.println("Nombre!!" + data[2]); modeloTabla.addRow(data); } tablaDialogo.setModel(modeloTabla); tablaDialogo.getColumn("ID").setMinWidth(70); tablaDialogo.getColumn("Identificacin").setMinWidth(60); tablaDialogo.getColumn("Nombre").setMinWidth(150); tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scroll = new JScrollPane(tablaDialogo); scroll.setPreferredSize(new Dimension(220, 150)); panelDialogo.add(scroll, c); c.insets = new Insets(0, 0, 0, 10); c.gridx = 0; c.gridy = 2; c.gridwidth = 1; JButton botonGuardarClienteDialogo = new JButton("Elegir"); panelDialogo.add(botonGuardarClienteDialogo, c); c.gridx = 1; c.gridy = 2; c.gridwidth = 1; JButton botonCerrarClienteDialogo = new JButton("Cancelar"); panelDialogo.add(botonCerrarClienteDialogo, c); dialogoEditar.add(panelDialogo); dialogoEditar.setVisible(true); botonCerrarClienteDialogo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialogoEditar.dispose(); } }); botonGuardarClienteDialogo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = tablaDialogo.getSelectedRow(); if (row == -1) { JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila"); } else { Object identificacionCliente = tablaDialogo.getValueAt(row, 0); Object idCliente = tablaDialogo.getValueAt(row, 1); mostrarIDProveedor.setText(String.valueOf(identificacionCliente)); String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 2)); //Limitar a 15 caracteres if (nombreClientePago.length() >= 15) { nombreClientePago = nombreClientePago.substring(0, 12); } textoNombreProveedor.setText(nombreClientePago); DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoProveedor.getModel(); for (int i = 0; i < modeloClientes.getRowCount(); i++) { modeloClientes.removeRow(i); } modeloClientes.setRowCount(0); ControladorFlujoCompras controladorFlujoCompra = new ControladorFlujoCompras(); //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506); ArrayList<Flujo_Compra> flujosProveedor = controladorFlujoCompra.obtenerFlujosCompras( " where ID_CompraProveedor in (select ID_CompraProveedor from Compra_Proveedores where IDProveedor = " + String.valueOf(identificacionCliente) + ") order by ID_CompraProveedor"); double pago = 0.0; for (int i = 0; i < flujosProveedor.size(); i++) { Flujo_Compra datos = flujosProveedor.get(i); Object[] rowData = { datos.getID_CompraProveedor(), datos.getTipo_flujo(), datos.getFecha(), datos.getMonto() }; if (datos.getTipo_flujo().equals("deuda")) { pago += Double.parseDouble(datos.getMonto() + ""); } else { pago -= Double.parseDouble(datos.getMonto() + ""); } modeloClientes.addRow(rowData); } TablaDeSaldoProveedor.setModel(modeloClientes); deudaActualProveedor.setText(String.valueOf(pago)); dialogoEditar.dispose(); //Mostrar en table de clientes los datos botonRegistrarAbono.setEnabled(true); } } }); }
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) {/*from w w w . j a v a 2 s .c om*/ 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 va 2 s . c om 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:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java
/** * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.) * @param tableArg the table that should have it's columns adjusted *///from w w w . j ava2 s . c o m private void initColumnSizes(final JTable tableArg, final JButton theSaveBtn) throws Exception { TableModel tblModel = tableArg.getModel(); TableColumn column = null; Component comp = null; int headerWidth = 0; int cellWidth = 0; Element uploadDefs = null; if (WorkbenchTask.isCustomizedSchema()) { uploadDefs = XMLHelper.readFileToDOM4J( new File(UIRegistry.getAppDataDir() + File.separator + "specify_workbench_upload_def.xml")); } else { uploadDefs = XMLHelper.readDOMFromConfigDir("specify_workbench_upload_def.xml"); } //UIRegistry.getInstance().hookUpUndoableEditListener(cellEditor); Vector<WorkbenchTemplateMappingItem> wbtmis = new Vector<WorkbenchTemplateMappingItem>(); wbtmis.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); Collections.sort(wbtmis); DBTableIdMgr databaseSchema = WorkbenchTask.getDatabaseSchema(); columnMaxWidths = new Integer[tableArg.getColumnCount()]; for (int i = 0; i < wbtmis.size() /*tableArg.getColumnCount()*/; i++) { TableCellRenderer headerRenderer = tableArg.getColumnModel().getColumn(i).getHeaderRenderer(); WorkbenchTemplateMappingItem wbtmi = wbtmis.elementAt(i); // Now go retrieve the data length int fieldWidth = WorkbenchDataItem.getMaxWBCellLength(); DBTableInfo ti = databaseSchema.getInfoById(wbtmi.getSrcTableId()); if (ti != null) { DBFieldInfo fi = ti.getFieldByName(wbtmi.getFieldName()); if (fi != null) { wbtmi.setFieldInfo(fi); //System.out.println(fi.getName()+" "+fi.getLength()+" "+fi.getType()); if (RecordTypeCodeBuilder.getTypeCode(fi) == null && fi.getLength() > 0) { fieldWidth = Math.min(fi.getLength(), WorkbenchDataItem.getMaxWBCellLength()); } } else { log.error("Can't find field with name [" + wbtmi.getFieldName() + "]"); } } else { log.error("Can't find table [" + wbtmi.getSrcTableId() + "]"); } columnMaxWidths[i] = new Integer(fieldWidth); GridCellEditor cellEditor = getCellEditor(wbtmi, fieldWidth, theSaveBtn, uploadDefs); column = tableArg.getColumnModel().getColumn(i); comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0); headerWidth = comp.getPreferredSize().width; comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg, tblModel.getValueAt(0, i), false, false, 0, i); cellWidth = comp.getPreferredSize().width; //comp.setBackground(Color.WHITE); int maxWidth = headerWidth + 10; TableModel m = tableArg.getModel(); FontMetrics fm = comp.getFontMetrics(comp.getFont()); for (int row = 0; row < tableArg.getModel().getRowCount(); row++) { String text = m.getValueAt(row, i).toString(); maxWidth = Math.max(maxWidth, fm.stringWidth(text) + 10); //log.debug(i+" "+maxWidth); } //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead. //log.debug(Math.max(maxWidth, cellWidth)); //log.debug(Math.min(Math.max(maxWidth, cellWidth), 400)); column.setPreferredWidth(Math.min(Math.max(maxWidth, cellWidth), 400)); column.setCellEditor(cellEditor); } //tableArg.setCellEditor(cellEditor); }
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;/* w w w . j av a2s . 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:com.mirth.connect.connectors.http.HttpListener.java
private void initComponentsManual() { staticResourcesTable.setModel(new RefreshTableModel(StaticResourcesColumn.getNames(), 0) { @Override// w w w . j a v a 2 s . c o m public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } }); staticResourcesTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); staticResourcesTable.setRowHeight(UIConstants.ROW_HEIGHT); staticResourcesTable.setFocusable(true); staticResourcesTable.setSortable(false); staticResourcesTable.setOpaque(true); staticResourcesTable.setDragEnabled(false); staticResourcesTable.getTableHeader().setReorderingAllowed(false); staticResourcesTable.setShowGrid(true, true); staticResourcesTable.setAutoCreateColumnsFromModel(false); staticResourcesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); staticResourcesTable.setRowSelectionAllowed(true); staticResourcesTable.setCustomEditorControls(true); if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) { staticResourcesTable.setHighlighters(HighlighterFactory .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR)); } class ContextPathCellEditor extends TextFieldCellEditor { public ContextPathCellEditor() { getTextField().setDocument(new MirthFieldConstraints("^\\S*$")); } @Override protected boolean valueChanged(String value) { if (StringUtils.isEmpty(value) || value.equals("/")) { return false; } if (value.equals(getOriginalValue())) { return false; } for (int i = 0; i < staticResourcesTable.getRowCount(); i++) { if (value.equals(fixContentPath((String) staticResourcesTable.getValueAt(i, StaticResourcesColumn.CONTEXT_PATH.getIndex())))) { return false; } } parent.setSaveEnabled(true); return true; } @Override public Object getCellEditorValue() { String value = fixContentPath((String) super.getCellEditorValue()); String baseContextPath = getBaseContextPath(); if (value.equals(baseContextPath)) { return null; } else { return fixContentPath(StringUtils.removeStartIgnoreCase(value, baseContextPath + "/")); } } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { String resourceContextPath = fixContentPath((String) value); setOriginalValue(resourceContextPath); getTextField().setText(getBaseContextPath() + resourceContextPath); return getTextField(); } } ; staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTEXT_PATH.getIndex()) .setCellEditor(new ContextPathCellEditor()); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTEXT_PATH.getIndex()) .setCellRenderer(new DefaultTableCellRenderer() { @Override protected void setValue(Object value) { super.setValue(getBaseContextPath() + fixContentPath((String) value)); } }); class ResourceTypeCellEditor extends MirthComboBoxTableCellEditor implements ActionListener { private Object originalValue; public ResourceTypeCellEditor(JTable table, Object[] items, int clickCount, boolean focusable) { super(table, items, clickCount, focusable, null); for (ActionListener actionListener : comboBox.getActionListeners()) { comboBox.removeActionListener(actionListener); } comboBox.addActionListener(this); } @Override public boolean stopCellEditing() { if (ObjectUtils.equals(getCellEditorValue(), originalValue)) { cancelCellEditing(); } else { parent.setSaveEnabled(true); } return super.stopCellEditing(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { originalValue = value; return super.getTableCellEditorComponent(table, value, isSelected, row, column); } @Override public void actionPerformed(ActionEvent evt) { ((AbstractTableModel) staticResourcesTable.getModel()).fireTableCellUpdated( staticResourcesTable.getSelectedRow(), StaticResourcesColumn.VALUE.getIndex()); stopCellEditing(); fireEditingStopped(); } } String[] resourceTypes = ResourceType.stringValues(); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()).setMinWidth(100); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()).setMaxWidth(100); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()) .setCellEditor(new ResourceTypeCellEditor(staticResourcesTable, resourceTypes, 1, false)); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()) .setCellRenderer(new MirthComboBoxTableCellRenderer(resourceTypes)); class ValueCellEditor extends AbstractCellEditor implements TableCellEditor { private JPanel panel; private JLabel label; private JTextField textField; private String text; private String originalValue; public ValueCellEditor() { panel = new JPanel(new MigLayout("insets 0 1 0 0, novisualpadding, hidemode 3")); panel.setBackground(UIConstants.BACKGROUND_COLOR); label = new JLabel(); label.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent evt) { new ValueDialog(); stopCellEditing(); } }); panel.add(label, "grow, pushx, h 19!"); textField = new JTextField(); panel.add(textField, "grow, pushx, h 19!"); } @Override public boolean isCellEditable(EventObject evt) { if (evt == null) { return false; } if (evt instanceof MouseEvent) { return ((MouseEvent) evt).getClickCount() >= 2; } return true; } @Override public Object getCellEditorValue() { if (label.isVisible()) { return text; } else { return textField.getText(); } } @Override public boolean stopCellEditing() { if (ObjectUtils.equals(getCellEditorValue(), originalValue)) { cancelCellEditing(); } else { parent.setSaveEnabled(true); } return super.stopCellEditing(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { boolean custom = table.getValueAt(row, StaticResourcesColumn.RESOURCE_TYPE.getIndex()) .equals(ResourceType.CUSTOM.toString()); label.setVisible(custom); textField.setVisible(!custom); panel.setBackground(table.getSelectionBackground()); label.setBackground(panel.getBackground()); label.setMaximumSize(new Dimension(table.getColumnModel().getColumn(column).getWidth(), 19)); String text = (String) value; this.text = text; originalValue = text; label.setText(text); textField.setText(text); return panel; } class ValueDialog extends MirthDialog { public ValueDialog() { super(parent, true); setTitle("Custom Value"); setPreferredSize(new Dimension(600, 500)); setLayout(new MigLayout("insets 12, novisualpadding, hidemode 3, fill", "", "[grow]7[]")); setBackground(UIConstants.BACKGROUND_COLOR); getContentPane().setBackground(getBackground()); final MirthSyntaxTextArea textArea = new MirthSyntaxTextArea(); textArea.setSaveEnabled(false); textArea.setText(text); textArea.setBorder(BorderFactory.createEtchedBorder()); add(textArea, "grow"); add(new JSeparator(), "newline, grow"); JPanel buttonPanel = new JPanel(new MigLayout("insets 0, novisualpadding, hidemode 3")); buttonPanel.setBackground(getBackground()); JButton openFileButton = new JButton("Open File..."); openFileButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String content = parent.browseForFileString(null); if (content != null) { textArea.setText(content); } } }); buttonPanel.add(openFileButton); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { text = textArea.getText(); label.setText(text); textField.setText(text); staticResourcesTable.getModel().setValueAt(text, staticResourcesTable.getSelectedRow(), StaticResourcesColumn.VALUE.getIndex()); parent.setSaveEnabled(true); dispose(); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { dispose(); } }); buttonPanel.add(cancelButton); add(buttonPanel, "newline, right"); pack(); setLocationRelativeTo(parent); setVisible(true); } } } ; staticResourcesTable.getColumnExt(StaticResourcesColumn.VALUE.getIndex()) .setCellEditor(new ValueCellEditor()); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()).setMinWidth(100); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()).setMaxWidth(150); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()) .setCellEditor(new TextFieldCellEditor() { @Override protected boolean valueChanged(String value) { if (value.equals(getOriginalValue())) { return false; } parent.setSaveEnabled(true); return true; } }); staticResourcesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { if (getSelectedRow(staticResourcesTable) != -1) { staticResourcesLastIndex = getSelectedRow(staticResourcesTable); staticResourcesDeleteButton.setEnabled(true); } else { staticResourcesDeleteButton.setEnabled(false); } } }); contextPathField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent evt) { changedUpdate(evt); } @Override public void removeUpdate(DocumentEvent evt) { changedUpdate(evt); } @Override public void changedUpdate(DocumentEvent evt) { ((AbstractTableModel) staticResourcesTable.getModel()).fireTableDataChanged(); } }); staticResourcesDeleteButton.setEnabled(false); }
From source file:interfaces.InterfazPrincipal.java
private void botonGenerarReporteClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGenerarReporteClienteActionPerformed // TODO add your handling code here: try {/*from w w w . j a v a 2s. c o m*/ if (clienteReporteClienteFechaFinal.getSelectedDate().getTime() .compareTo(clienteReporteClienteFechaInicial.getSelectedDate().getTime()) < 0) { JOptionPane.showMessageDialog(this, "La fecha final debe ser posterior al dia de inicio"); } else { final ArrayList<Integer> listaIDFlujos = new ArrayList<>(); final JDialog dialogoEditar = new JDialog(); dialogoEditar.setTitle("Reporte cliente"); dialogoEditar.setSize(350, 610); dialogoEditar.setResizable(false); JPanel panelDialogo = new JPanel(); panelDialogo.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //c.fill = GridBagConstraints.HORIZONTAL; JLabel ediitarTextoPrincipalDialogo = new JLabel("Informe cliente"); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.insets = new Insets(10, 45, 10, 10); Font textoGrande = new Font("Arial", 1, 18); ediitarTextoPrincipalDialogo.setFont(textoGrande); panelDialogo.add(ediitarTextoPrincipalDialogo, c); final JTable tablaDialogo = new JTable(); DefaultTableModel modeloTabla = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { //all cells false return false; } }; ; modeloTabla.addColumn("Factura"); modeloTabla.addColumn("Tipo Flujo"); modeloTabla.addColumn("Fecha"); modeloTabla.addColumn("Valor"); //Llenar tabla ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura(); ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura( " where factura_id in (select factura_id from Factura where cliente_id = " + String.valueOf(jTextFieldIdentificacionClienteReporte.getText()) + ") order by factura_id"); // {"flujo_id","factura_id","tipo_flujo","fecha","valor"}; ArrayList<Calendar> fechasFlujos = new ArrayList<>(); for (int i = 0; i < flujosCliente.size(); i++) { String fila[] = new String[4]; String[] objeto = flujosCliente.get(i); fila[0] = objeto[1]; fila[1] = objeto[2]; fila[2] = objeto[3]; fila[3] = objeto[4]; //Filtrar, mirar las fechas String[] partirEspacios = objeto[3].split("\\s"); //El primer string es la fecha sin hora //Ahora esparamos por - String[] tomarAgeMesDia = partirEspacios[0].split("-"); //Realizar filtro int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]); int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]); int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]); //Obtenemos dias, mes y ao de la consulta //Inicial int anioInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.YEAR); int mesInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.MONTH) + 1; int diaInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.DAY_OF_MONTH); //Final int anioFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.YEAR); int mesFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.MONTH) + 1; int diaFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.DAY_OF_MONTH); //Construir fechas Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta); //Set year, month, day) Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial); Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal); if (fechaDeLaBD.compareTo(fechaInicialRango) <= 0 && fechaDeLaBD.compareTo(fechaFinalRango) >= 0) { fechasFlujos.add(fechaDeLaBD); modeloTabla.addRow(fila); } } if (modeloTabla.getRowCount() > 0) { tablaDialogo.setModel(modeloTabla); tablaDialogo.getColumn("Factura").setMinWidth(80); tablaDialogo.getColumn("Tipo Flujo").setMinWidth(80); tablaDialogo.getColumn("Fecha").setMinWidth(90); tablaDialogo.getColumn("Valor").setMinWidth(80); tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scroll = new JScrollPane(tablaDialogo); scroll.setPreferredSize(new Dimension(330, 150)); c.gridx = 0; c.gridy = 1; c.gridwidth = 1; c.insets = new Insets(0, 0, 0, 0); panelDialogo.add(scroll, c); TimeSeries localTimeSeries = new TimeSeries("Compras del cliente en el periodo"); Map listaAbonos = new HashMap(); for (int i = 0; i < modeloTabla.getRowCount(); i++) { listaIDFlujos.add(Integer.parseInt(flujosCliente.get(i)[0])); if (modeloTabla.getValueAt(i, 1).equals("abono")) { Calendar fechaFlujo = fechasFlujos.get(i); double valor = Double.parseDouble(String.valueOf(modeloTabla.getValueAt(i, 3))); int anoDato = fechaFlujo.get(Calendar.YEAR); int mesDato = fechaFlujo.get(Calendar.MONTH) + 1; int diaDato = fechaFlujo.get(Calendar.DAY_OF_MONTH); Day FechaDato = new Day(diaDato, mesDato, anoDato); if (listaAbonos.get(FechaDato) != null) { double valorAbono = (double) listaAbonos.get(FechaDato); listaAbonos.remove(FechaDato); listaAbonos.put(FechaDato, valorAbono + valor); } else { listaAbonos.put(FechaDato, valor); } } } Double maximo = 0.0; Iterator iterator = listaAbonos.keySet().iterator(); while (iterator.hasNext()) { Day key = (Day) iterator.next(); Double value = (double) listaAbonos.get(key); maximo = Math.max(maximo, value); localTimeSeries.add(key, value); } //localTimeSeries.add(); TimeSeriesCollection datos = new TimeSeriesCollection(localTimeSeries); JFreeChart chart = ChartFactory.createTimeSeriesChart("Compras del cliente en el periodo", // Title "Tiempo", // x-axis Label "Total ($)", // y-axis Label datos, // Dataset true, // Show Legend true, // Use tooltips false // Configure chart to generate URLs? ); /*Altering the graph */ XYPlot plot = (XYPlot) chart.getPlot(); plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis(); numberAxis.setRange(new Range(0, maximo * 1.2)); Font font = new Font("Dialog", Font.PLAIN, 9); numberAxis.setTickLabelFont(font); numberAxis.setLabelFont(font); DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy")); axis.setAutoTickUnitSelection(false); axis.setVerticalTickLabels(true); axis.setTickLabelFont(font); axis.setLabelFont(font); LegendTitle leyendaChart = chart.getLegend(); leyendaChart.setItemFont(font); Font fontTitulo = new Font("Dialog", Font.BOLD, 12); TextTitle tituloChart = chart.getTitle(); tituloChart.setFont(fontTitulo); ChartPanel CP = new ChartPanel(chart); Dimension D = new Dimension(330, 300); CP.setPreferredSize(D); CP.setVisible(true); c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.insets = new Insets(10, 0, 0, 0); panelDialogo.add(CP, c); c.gridx = 0; c.gridy = 3; c.gridwidth = 1; c.anchor = GridBagConstraints.WEST; c.insets = new Insets(10, 30, 0, 0); JButton botonCerrar = new JButton("Cerrar"); botonCerrar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialogoEditar.dispose(); } }); panelDialogo.add(botonCerrar, c); JButton botonGenerarPDF = new JButton("Guardar archivo"); botonGenerarPDF.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente(); reporteFlujosCliente.guardarDocumentoDialogo(dialogoEditar, listaIDFlujos, Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()), clienteReporteClienteFechaInicial.getSelectedDate(), clienteReporteClienteFechaFinal.getSelectedDate()); } }); c.insets = new Insets(10, 100, 0, 0); panelDialogo.add(botonGenerarPDF, c); JButton botonImprimir = new JButton("Imprimir"); botonImprimir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente(); reporteFlujosCliente.imprimirFlujo(listaIDFlujos, Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()), clienteReporteClienteFechaInicial.getSelectedDate(), clienteReporteClienteFechaFinal.getSelectedDate()); } }); c.insets = new Insets(10, 230, 0, 0); panelDialogo.add(botonImprimir, c); dialogoEditar.add(panelDialogo); dialogoEditar.setVisible(true); } else { JOptionPane.showMessageDialog(this, "El cliente no registra movimientos en el rango de fechas seleccionado"); } } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Debe seleccionar un da inicial y final de fechas"); } }
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 w w w . j a va2 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:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java
private void setJobQueueTableDefaults(JTable jobQueueTable, JobQueueTableModel jobQueueTableModel) { jobQueueTableModel.addTableModelListener(new JobQueueTableModelListener()); jobQueueTable.setModel(jobQueueTableModel); jobQueueTable.setSurrendersFocusOnKeystroke(true); jobQueueTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); jobQueueTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); jobQueueTable.setColumnSelectionAllowed(true); jobQueueTable.setRowSelectionAllowed(true); TableRenderer renderer = new TableRenderer(); TableColumn col = jobQueueTable.getColumnModel().getColumn(0); int width = 200; col.setPreferredWidth(width);/*from w w w .ja v a2 s . c o m*/ col.setWidth(width); col.setCellRenderer(renderer); col = jobQueueTable.getColumnModel().getColumn(1); width = 1400; col.setPreferredWidth(width); col.setWidth(width); col.setCellRenderer(renderer); }
From source file:org.apache.cayenne.modeler.editor.ObjEntityRelationshipPanel.java
protected void rebuildTable(ObjEntity entity) { final ObjRelationshipTableModel model = new ObjRelationshipTableModel(entity, mediator, this); model.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { if (table.getSelectedRow() >= 0) { ObjRelationship rel = model.getRelationship(table.getSelectedRow()); enabledResolve = rel.getSourceEntity().getDbEntity() != null; resolveMenu.setEnabled(enabledResolve); }/*from w w w . j ava 2s . c o m*/ } }); table.setModel(model); table.setRowHeight(25); table.setRowMargin(3); TableColumn col = table.getColumnModel().getColumn(ObjRelationshipTableModel.REL_TARGET_PATH); col.setCellEditor(new DbRelationshipPathComboBoxEditor()); col.setCellRenderer(new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); setToolTipText( "To choose relationship press enter two times.To choose next relationship press dot."); return this; } }); col = table.getColumnModel().getColumn(ObjRelationshipTableModel.REL_DELETE_RULE); JComboBox deleteRulesCombo = Application.getWidgetFactory().createComboBox(DELETE_RULES, false); deleteRulesCombo.setFocusable(false); deleteRulesCombo.setEditable(true); ((JComponent) deleteRulesCombo.getEditor().getEditorComponent()).setBorder(null); deleteRulesCombo.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); deleteRulesCombo.setSelectedIndex(0); // Default to the first value col.setCellEditor(Application.getWidgetFactory().createCellEditor(deleteRulesCombo)); tablePreferences.bind(table, null, null, null, ObjRelationshipTableModel.REL_NAME, true); }