List of usage examples for java.lang Math rint
public static double rint(double a)
From source file:ejemplo.grafica.java
private void valoresPertenecia() { double nivel = parseDouble(txtNivel.getText()); double peso = parseDouble(txtPeso.getText()); double tipo = parseDouble(txtTipo.getText()); double porcentajeN, porcentajeP, porcentajeT, complementoN, complementoP, complementoT; double aN = parseDouble(txtMinNivel.getText()), aP = parseDouble(txtMinPeso.getText()), aT = parseDouble(txtMinTipo.getText()); double bN = parseDouble(txtMaxNivel.getText()), bP = parseDouble(txtMaxPeso.getText()), bT = parseDouble(txtMaxTipo.getText()); double mN = (aN + bN) / 2; double mP = (aP + bP) / 2; double mT = (aT + bT) / 2; String arregloSuciedad[], arregloPeso[]; String mensajeNivel, mensajePeso, mensajeTipo, bandera; if (nivel >= aN && nivel <= mN) { porcentajeN = (nivel - aN) / (mN - aN); complementoN = 1 - porcentajeN;/*www.j av a 2s. c o m*/ mensajeNivel = "El Nivel de Suciedad Pertenece en un " + Math.rint(porcentajeN * 100) + "% Al Conjunto Difuso Sucia y en un " + Math.rint(complementoN * 100) + "% Al Conjunto Difuso de Poco Sucia"; arregloSuciedad = mayorSuciedad(porcentajeN, complementoN, 0); } else { porcentajeN = (bN - nivel) / (bN - mN); complementoN = 1 - porcentajeN; mensajeNivel = "El Nivel de Suciedad Pertenece en un " + Math.rint(porcentajeN * 100) + "% Al Conjunto Difuso Sucia y en un " + Math.rint(complementoN * 100) + "% Al Conjunto Difuso Muy Sucia "; arregloSuciedad = mayorSuciedad(porcentajeN, complementoN, 1); } if (peso >= aP && peso <= mP) { porcentajeP = (peso - aP) / (mP - aP); complementoP = 1 - porcentajeP; mensajePeso = "El Nivel de Peso Pertenece en un " + Math.rint(porcentajeP * 100) + "% Al Conjunto Difuso Pesado y en un " + Math.rint(complementoP * 100) + "% Al Conjunto Difuso Liviano"; arregloPeso = mayorPeso(porcentajeP, complementoP, 0); } else { porcentajeP = (bP - peso) / (bP - mP); complementoP = 1 - porcentajeP; mensajePeso = "El Nivel de Peso Pertenece en un " + Math.rint(porcentajeP * 100) + "% Al Conjunto Difuso Pesado y en un " + Math.rint(complementoP * 100) + "% Al Conjunto Difuso Muy Pesado"; arregloPeso = mayorPeso(porcentajeP, complementoP, 1); } if (tipo >= aT && tipo <= mT) { porcentajeT = (tipo - aT) / (mT - aT); complementoT = 1 - porcentajeT; mensajeTipo = "El Nivel de Tipo de Ropa Pertenece en un " + Math.rint(porcentajeT * 100) + "% Al Conjunto Difuso de Jeans y en un " + Math.rint(complementoT * 100) + "% Al Conjunto Difuso de Algodon"; } else { porcentajeT = (bT - tipo) / (bT - mT); complementoT = 1 - porcentajeT; mensajeTipo = "El Nivel de Tipo de Ropa Pertenece en un " + Math.rint(porcentajeT * 100) + "% Al Conjunto Difuso de Jeans y en un " + Math.rint(complementoT * 100) + "% Al Conjunto Difuso de Seda"; } sistemaReglaDetergente(arregloSuciedad, arregloPeso); sistemaReglaTiempoLavado(arregloSuciedad, arregloPeso); sistemaReglaTipoLavado(arregloSuciedad, arregloPeso); textAreaEntradas.setText(""); textAreaEntradas.append(mensajeNivel); textAreaEntradas.append(System.getProperty("line.separator")); textAreaEntradas.append(mensajePeso); textAreaEntradas.append(System.getProperty("line.separator")); textAreaEntradas.append(mensajeTipo); }
From source file:com.kodemore.utility.Kmu.java
/** * Round the double to the next whole number. *///w w w.jav a2 s . com public static double roundHalfUpToInteger(double d) { return Math.rint(d); }
From source file:org.gumtree.vis.plot1d.LogarithmizableAxis.java
private List getAllTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { // TODO Auto-generated method stub List ticks = new java.util.ArrayList(); Range range = getRange();//www. ja v a 2 s . c om //get lower bound value: double lowerBoundVal = range.getLowerBound(); //if small log values and lower bound value too small // then set to a small value (don't allow <= 0): if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) { lowerBoundVal = SMALL_LOG_VALUE; } //get upper bound value double upperBoundVal = range.getUpperBound(); //get log10 version of lower bound and round to integer: int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal)); //get log10 version of upper bound and round to integer: int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal)); // if (iBegCount == iEndCount && iBegCount >= 0 if (iBegCount == iEndCount && Math.pow(10, iBegCount) > lowerBoundVal) { //only 1 power of 10 value, it's > 0 and its resulting // tick value will be larger than lower bound of data --iBegCount; //decrement to generate more ticks } int numberOfGrids = 0; int numberOfTicks = 0; NumberTick lastTick = null; double currentTickValue; String tickLabel; boolean zeroTickFlag = false; for (int i = iBegCount; i <= iEndCount; i++) { //for each power of 10 value; create ten ticks for (int j = 0; j < 10; ++j) { //for each tick to be displayed if (this.smallLogFlag) { //small log values in use; create numeric value for tick currentTickValue = Math.pow(10, i) + (Math.pow(10, i) * j); if (this.expTickLabelsFlag || (i < 0 && currentTickValue > 0.0 && currentTickValue < 1.0)) { //showing "1e#"-style ticks or negative exponent // generating tick value between 0 & 1; show fewer //first tick of series, or not too small a value and // one of first 3 ticks, or last tick to be displayed // set exact number of fractional digits to be shown // (no effect if showing "1e#"-style ticks): this.numberFormatterObj.setMaximumFractionDigits(-i); //create tick label (force use of fmt obj): tickLabel = makeTickLabel(currentTickValue, true); } else { //tick value not between 0 & 1 //show tick label if it's the first or last in // the set, or if it's 1-5; beyond that show // fewer as the values get larger: tickLabel = makeTickLabel(currentTickValue); } } else { //not small log values in use; allow for values <= 0 if (zeroTickFlag) { //if did zero tick last iter then --j; //decrement to do 1.0 tick now } //calculate power-of-ten value for tick: currentTickValue = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j) : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j)); if (!zeroTickFlag) { // did not do zero tick last iteration if (Math.abs(currentTickValue - 1.0) < 0.0001 && lowerBoundVal <= 0.0 && upperBoundVal >= 0.0) { //tick value is 1.0 and 0.0 is within data range currentTickValue = 0.0; //set tick value to zero zeroTickFlag = true; //indicate zero tick } } else { //did zero tick last iteration zeroTickFlag = false; //clear flag } //create tick label string: //show tick label if "1e#"-style and it's one // of the first two, if it's the first or last // in the set, or if it's 1-5; beyond that // show fewer as the values get larger: tickLabel = makeTickLabel(currentTickValue); } if (currentTickValue > upperBoundVal) { if (lastTick != null) { String lastTickText = lastTick.getText(); if (lastTickText == null || lastTickText.trim().length() == 0) { ticks.remove(lastTick); ticks.add(new NumberTick(lastTick.getValue(), createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(), lastTick.getRotationAnchor(), lastTick.getAngle())); } } if (ticks.size() < 2) { double definition = Math.abs(lowerBoundVal - upperBoundVal); int numberOfDigits = 0; if (definition >= 1) numberOfDigits = 0; else { numberOfDigits = (int) Math.ceil((-Math.log10(definition))); } if (definition < 2 * Math.pow(10, -numberOfDigits)) { numberOfDigits++; } double tickVal; tickVal = lowerBoundVal; if (definition > 1) tickLabel = Long.toString((long) Math.rint(tickVal)); else tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); tickVal = upperBoundVal; if (definition > 1) { tickLabel = Long.toString((long) Math.rint(tickVal)); } else { tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); } ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); } return ticks; // if past highest data value then exit // method } if (currentTickValue >= lowerBoundVal - SMALL_LOG_VALUE) { //tick value not below lowest data value TextAnchor anchor = null; TextAnchor rotationAnchor = null; double angle = 0.0; if (isVerticalTickLabels()) { anchor = TextAnchor.CENTER_RIGHT; rotationAnchor = TextAnchor.CENTER_RIGHT; if (edge == RectangleEdge.TOP) { angle = Math.PI / 2.0; } else { angle = -Math.PI / 2.0; } } else { if (edge == RectangleEdge.TOP) { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; } else { anchor = TextAnchor.TOP_CENTER; rotationAnchor = TextAnchor.TOP_CENTER; } } lastTick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle); ticks.add(lastTick); if (tickLabel != null && tickLabel.trim().length() > 0) numberOfTicks++; numberOfGrids++; } } } if (ticks.size() < 2) { double definition = Math.abs(lowerBoundVal - upperBoundVal); int numberOfDigits = 0; if (definition >= 1) numberOfDigits = 0; else { numberOfDigits = (int) Math.ceil((-Math.log10(definition))); } double tickVal; tickVal = lowerBoundVal; if (definition > 1) tickLabel = Long.toString((long) Math.rint(tickVal)); else tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); tickVal = upperBoundVal; if (definition > 1) tickLabel = Long.toString((long) Math.rint(tickVal)); else tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); } return ticks; }
From source file:org.gumtree.vis.plot1d.LogarithmizableAxis.java
/** * Create tick label /*from ww w.ja va 2s . c om*/ */ private String createTickLabel(double tickVal, int index) { String tickLabel; String initial = "1"; // if (tickVal > 1) double value = tickVal / Math.pow(10, index); if (tickVal > 10) { initial = String.valueOf((int) value); } else { initial = String.format("%.1f", value); } if (this.log10TickLabelsFlag) { //create "log10"-type label tickLabel = (((index < 0) ? "-" : "") + "10^" + Math.abs(index)); } else { if (this.expTickLabelsFlag) { //create "1e#"-type label tickLabel = (((index < 0) ? "-" : "") + initial + "e" + Math.abs(index)); } else { if (tickVal > 1) { NumberFormat format = getNumberFormatOverride(); if (format != null) { tickLabel = format.format(tickVal); } else { tickLabel = Long.toString((long) Math.rint(tickVal)); } } else { this.numberFormatterObj.setMaximumFractionDigits(-index); // create tick label: tickLabel = this.numberFormatterObj.format(tickVal); } } } return tickLabel; }
From source file:org.sakaiproject.tool.gradebook.business.impl.GradebookManagerHibernateImpl.java
@Override public boolean validateCategoryWeighting(Long gradebookId) { Gradebook gradebook = getGradebook(gradebookId); if (gradebook.getCategory_type() != GradebookService.CATEGORY_TYPE_WEIGHTED_CATEGORY) return true; List cats = getCategories(gradebookId); double weight = 0.0; for (int i = 0; i < cats.size(); i++) { Category cat = (Category) cats.get(i); if (cat != null) { weight += cat.getWeight().doubleValue(); }//from ww w . j ava 2 s . c o m } if (Math.rint(weight) == 1) return true; else return false; }
From source file:de.tor.tribes.ui.windows.DSWorkbenchMainFrame.java
private void refreshMap() { //ensure that within map range Rectangle mapDim = ServerSettings.getSingleton().getMapDimension(); if (dCenterX < mapDim.getMinX() || dCenterX > mapDim.getMaxX() || dCenterY < mapDim.getMinY() || dCenterY > mapDim.getMaxX()) { //find out where we tried to leaf map and set these valuese to max / min if (dCenterX < mapDim.getMinX()) { dCenterX = (int) mapDim.getMinX(); jCenterX.setText(Integer.toString((int) dCenterX)); } else if (dCenterX > mapDim.getMaxX()) { dCenterX = (int) mapDim.getMaxX(); jCenterX.setText(Integer.toString((int) dCenterX)); }//from ww w. j a v a2s . co m if (dCenterY < mapDim.getMinY()) { dCenterY = (int) mapDim.getMinY(); jCenterY.setText(Integer.toString((int) dCenterY)); } else if (dCenterY > mapDim.getMaxX()) { dCenterY = (int) mapDim.getMaxX(); jCenterY.setText(Integer.toString((int) dCenterY)); } } double w = (double) MapPanel.getSingleton().getWidth() / GlobalOptions.getSkin().getBasicFieldWidth() * dZoomFactor; double h = (double) MapPanel.getSingleton().getHeight() / GlobalOptions.getSkin().getBasicFieldHeight() * dZoomFactor; MinimapPanel.getSingleton().setSelection((int) Math.floor(dCenterX), (int) Math.floor(dCenterY), (int) Math.rint(w), (int) Math.rint(h)); MapPanel.getSingleton().updateMapPosition(dCenterX, dCenterY, true); }
From source file:org.sakaiproject.component.gradebook.GradebookServiceHibernateImpl.java
@Override public void updateGradebookSettings(String gradebookUid, GradebookInformation gbInfo) { if (gradebookUid == null) { throw new IllegalArgumentException("null gradebookUid " + gradebookUid); }// www .ja v a 2s . c o m //must be instructor type person if (!currentUserHasEditPerm(gradebookUid)) { log.error("AUTHORIZATION FAILURE: User " + getUserUid() + " in gradebook " + gradebookUid + " attempted to edit gb information"); throw new SecurityException( "You do not have permission to edit gradebook information in site " + gradebookUid); } final Gradebook gradebook = getGradebook(gradebookUid); if (gradebook == null) { throw new IllegalArgumentException("There is no gradebook associated with this id: " + gradebookUid); } //iterate all available grademappings for this gradebook and set the one that we have the ID for Set<GradeMapping> gradeMappings = gradebook.getGradeMappings(); for (GradeMapping gradeMapping : gradeMappings) { if (StringUtils.equals(Long.toString(gradeMapping.getId()), gbInfo.getSelectedGradeMappingId())) { gradebook.setSelectedGradeMapping(gradeMapping); //update the map values updateGradeMapping(gradeMapping.getId(), gbInfo.getSelectedGradingScaleBottomPercents()); } } //set grade type gradebook.setGrade_type(gbInfo.getGradeType()); //set category type gradebook.setCategory_type(gbInfo.getCategoryType()); //set display release items to students gradebook.setAssignmentsDisplayed(gbInfo.isDisplayReleasedGradeItemsToStudents()); //set course grade display settings gradebook.setCourseGradeDisplayed(gbInfo.isCourseGradeDisplayed()); gradebook.setCourseLetterGradeDisplayed(gbInfo.isCourseLetterGradeDisplayed()); gradebook.setCoursePointsDisplayed(gbInfo.isCoursePointsDisplayed()); gradebook.setCourseAverageDisplayed(gbInfo.isCourseAverageDisplayed()); List<CategoryDefinition> newCategoryDefinitions = gbInfo.getCategories(); //if we have categories and they are weighted, check the weightings sum up to 100% (or 1 since it's a fraction) if (gradebook.getCategory_type() == GradebookService.CATEGORY_TYPE_WEIGHTED_CATEGORY) { double totalWeight = 0; for (CategoryDefinition newDef : newCategoryDefinitions) { if (newDef.getWeight() == null) { throw new IllegalArgumentException( "No weight specified for a category, but weightings enabled"); } totalWeight += newDef.getWeight(); } if (Math.rint(totalWeight) != 1) { throw new IllegalArgumentException("Weightings for the categories do not equal 100%"); } } //get current categories and build a mapping list of Category.id to Category List<Category> currentCategories = this.getCategories(gradebook.getId()); Map<Long, Category> currentCategoryMap = new HashMap<>(); for (Category c : currentCategories) { currentCategoryMap.put(c.getId(), c); } //compare current list with given list, add/update/remove as required //Rules: //If category does not have an ID it is new //If category has an ID it is to be updated. Update and remove from currentCategoryMap. //Any categories remaining in currentCategoryMap are to be removed. for (CategoryDefinition newDef : newCategoryDefinitions) { //preprocessing and validation //Rule 1: If category has no name, it is to be removed/skipped //Note that we no longer set weights to 0 even if unweighted category type selected. The weights are not considered if its not a weighted category type //so this allows us to switch back and forth between types without losing information if (StringUtils.isBlank(newDef.getName())) { continue; } //new if (newDef.getId() == null) { this.createCategory(gradebook.getId(), newDef.getName(), newDef.getWeight(), newDef.getDrop_lowest(), newDef.getDropHighest(), newDef.getKeepHighest(), newDef.isExtraCredit()); continue; } //update else { Category existing = currentCategoryMap.get(newDef.getId()); existing.setName(newDef.getName()); existing.setWeight(newDef.getWeight()); existing.setDrop_lowest(newDef.getDrop_lowest()); existing.setDropHighest(newDef.getDropHighest()); existing.setKeepHighest(newDef.getKeepHighest()); existing.setExtraCredit(newDef.isExtraCredit()); this.updateCategory(existing); //remove from currentCategoryMap so we know not to delete it currentCategoryMap.remove(newDef.getId()); continue; } } //handle deletes //anything left in currentCategoryMap was not included in the new list, delete them for (Entry<Long, Category> cat : currentCategoryMap.entrySet()) { this.removeCategory(cat.getKey()); } //no need to set assignments, gbInfo doesn't update them //persist this.updateGradebook(gradebook); }
From source file:com.cohort.util.String2.java
/** * This returns the number formatted with up to 6 digits to the left and right of * the decimal and trailing decimal 0's removed. * If abs(d) < 0.0999995 or abs(d) >= 999999.9999995, the number is displayed * in scientific notation (e.g., 8.954321E-5). * Thus the maximum length should be 14 characters (-123456.123456). * 0 returns "0"//from w w w. j a va2 s.c o m * NaN returns "NaN". * Double.POSITIVE_INFINITY returns "Infinity". * Double.NEGATIVE_INFINITY returns "-Infinity". * * @param d a number * @return the number converted to a string */ public static String genEFormat6(double d) { //!finite if (!Double.isFinite(d)) return "" + d; //almost 0 if (Math2.almost0(d)) return "0"; //close to 0 //String2.log("genEFormat test " + (d*1000) + " " + Math.rint(d*1000)); if (Math.abs(d) < 0.0999995 && !Math2.almostEqual(6, d * 10000, Math.rint(d * 10000))) { //leave .0021 as .0021, but display .00023 as 2.3e-4 synchronized (genExpFormat6) { return genExpFormat6.format(d); } } //large int if (Math.abs(d) < 1e13 && d == Math.rint(d)) return "" + Math2.roundToLong(d); //>10e6 if (Math.abs(d) >= 999999.9999995) { synchronized (genExpFormat6) { return genExpFormat6.format(d); } } synchronized (genStdFormat6) { return genStdFormat6.format(d); } }
From source file:com.cohort.util.String2.java
/** * This returns the number formatted with up to 10 digits to the left and right of * the decimal and trailing decimal 0's removed. * If abs(d) < 0.09999999995 or abs(d) >= 999999.99999999995, the number is displayed * in scientific notation (e.g., 8.9544680321E-5). * Thus the maximum length should be 18 characters (-123456.1234567898). * 0 returns "0"//from w ww. ja v a 2 s. c o m * NaN returns "NaN". * Double.POSITIVE_INFINITY returns "Infinity". * Double.NEGATIVE_INFINITY returns "-Infinity". * * @param d a number * @return the number converted to a string */ public static String genEFormat10(double d) { //!finite if (!Double.isFinite(d)) return "" + d; //almost 0 if (Math2.almost0(d)) return "0"; //close to 0 and many sig digits //String2.log("genEFormat test " + (d*1000) + " " + Math.rint(d*1000)); if (Math.abs(d) < 0.09999999995 && !Math2.almostEqual(9, d * 1000000, Math.rint(d * 1000000))) { //leave .0021 as .0021, but display .00023 as 2.3e-4 synchronized (genExpFormat10) { return genExpFormat10.format(d); } } //large int if (Math.abs(d) < 1e13 && d == Math.rint(d)) //rint only catches 9 digits(?) return "" + Math2.roundToLong(d); //>10e6 if (Math.abs(d) >= 999999.99999999995) { synchronized (genExpFormat10) { return genExpFormat10.format(d); } } synchronized (genStdFormat10) { return genStdFormat10.format(d); } }
From source file:de.tor.tribes.ui.windows.TribeTribeAttackFrame.java
/** * Create detail frames shown after calculation *//* ww w . j av a 2 s .c o m*/ private void buildDetailedStatistics(HashMap<Village, String> attackMappings, List<Village> pNotAssignedVillages) { // <editor-fold defaultstate="collapsed" desc="Build not assigned source table"> Collections.sort(pNotAssignedVillages); DefaultTableModel sourcesModel = new javax.swing.table.DefaultTableModel(new Object[][] {}, new String[] { "Spieler", "Dorf" }) { private Class[] cTypes = new Class[] { Tribe.class, Village.class }; @Override public Class getColumnClass(int columnIndex) { return cTypes[columnIndex]; } }; for (Village notAssigned : pNotAssignedVillages) { Tribe t = notAssigned.getTribe(); if (t == null) { sourcesModel.addRow(new Object[] { Barbarians.getSingleton(), notAssigned }); } else { sourcesModel.addRow(new Object[] { t, notAssigned }); } } jNotAssignedSourcesTable.setModel(sourcesModel); TableRowSorter<TableModel> sourcesSorter = new TableRowSorter<TableModel>(sourcesModel); jNotAssignedSourcesTable.setRowSorter(sourcesSorter); DefaultTableCellRenderer headerRenderer = new SortableTableHeaderRenderer(); for (int i = 0; i < jNotAssignedSourcesTable.getColumnCount(); i++) { jNotAssignedSourcesTable.getColumn(jNotAssignedSourcesTable.getColumnName(i)) .setHeaderRenderer(headerRenderer); } jNotAssignedSourcesTable.revalidate(); //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Build attacks per target table"> DefaultTableModel tableModel = new javax.swing.table.DefaultTableModel(new Object[][] {}, new String[] { "Spieler", "Dorf", "Angriffe" }) { Class[] types = new Class[] { Tribe.class, Village.class, String.class }; @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } }; List<Village> notFullTargets = new LinkedList<Village>(); Iterator<Village> keys = attackMappings.keySet().iterator(); while (keys.hasNext()) { Village key = keys.next(); Tribe t = key.getTribe(); //int notAssignedAmount = attackMappings.get(key); String attackCount = attackMappings.get(key); String[] split = attackCount.split("/"); int notAssignedAmount = Integer.parseInt(split[1]) - Integer.parseInt(split[0]); if (t != Barbarians.getSingleton()) { tableModel.addRow(new Object[] { t, key, attackCount }); } else { tableModel.addRow(new Object[] { "Barbaren", key, attackCount }); } if (notAssignedAmount > 0) { notFullTargets.add(key); } } jTargetDetailsTable.setModel(tableModel); TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel); jTargetDetailsTable.setRowSorter(sorter); DefaultTableCellRenderer coloredRenderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = new DefaultTableCellRenderer().getTableCellRendererComponent(table, value, isSelected, hasFocus, row, row); String t = ((DefaultTableCellRenderer) c).getText(); ((DefaultTableCellRenderer) c).setText(t); DefaultTableModel model = (DefaultTableModel) table.getModel(); int r = table.convertRowIndexToModel(row); String sVal = (String) model.getValueAt(r, 2); String[] split = sVal.split("/"); long max = Long.parseLong(split[1]); long v = Long.parseLong(split[0]); long diff = max - v; Color back = Color.RED; if (v == 0) { //color stays red } else if (v == max) { back = Color.GREEN; } else { float posv = 100.0f * (float) diff / (float) max; posv = ((int) posv / 10) * 10; posv /= 100; Color LAST_SEGMENT = new Color(255, 100, 0); int red = (int) Math.rint( (float) LAST_SEGMENT.getRed() * (1.0f - posv) + (float) Color.YELLOW.getRed() * posv); int green = (int) Math.rint((float) LAST_SEGMENT.getGreen() * (1.0f - posv) + (float) Color.YELLOW.getGreen() * posv); int blue = (int) Math.rint( (float) LAST_SEGMENT.getBlue() * (1.0f - posv) + (float) Color.YELLOW.getBlue() * posv); if (red < 0) { red = 0; } if (green < 0) { green = 0; } if (blue < 0) { blue = 0; } if (red > 254) { red = 254; } if (green > 254) { green = 254; } if (blue > 254) { blue = 254; } back = new Color(red, green, blue); } DefaultTableCellRenderer renderer = ((DefaultTableCellRenderer) c); if (!isSelected) { renderer.setBackground(back); } return c; } }; jTargetDetailsTable.setDefaultRenderer(Village.class, coloredRenderer); jTargetDetailsTable.setDefaultRenderer(Integer.class, coloredRenderer); jTargetDetailsTable.setDefaultRenderer(String.class, coloredRenderer); jTargetDetailsTable.setDefaultRenderer(Tribe.class, coloredRenderer); for (int i = 0; i < jTargetDetailsTable.getColumnCount(); i++) { jTargetDetailsTable.getColumn(jTargetDetailsTable.getColumnName(i)).setHeaderRenderer(headerRenderer); } jTargetDetailsTable.revalidate(); //</editor-fold> }