Example usage for java.awt Color decode

List of usage examples for java.awt Color decode

Introduction

In this page you can find the example usage for java.awt Color decode.

Prototype

public static Color decode(String nm) throws NumberFormatException 

Source Link

Document

Converts a String to an integer and returns the specified opaque Color .

Usage

From source file:org.tellervo.desktop.prefs.Prefs.java

private void installUIDefault(Class<? extends Object> type, String prefskey, String uikey) {
    Object decoded = null;/*from  w ww .  j av a 2  s  .  c  o m*/
    String pref = prefs.getProperty(prefskey);
    if (pref == null) {
        log.warn("Preference '" + prefskey + "' held null value.");
        return;
    }
    if (Color.class.isAssignableFrom(type)) {
        decoded = Color.decode(pref);
    } else if (Font.class.isAssignableFrom(type)) {
        decoded = Font.decode(pref);
    } else {
        log.warn("Unsupported UIDefault preference type: " + type);
        return;
    }

    if (decoded == null) {
        log.warn("UIDefaults color preference '" + prefskey + "' was not decodable.");
        return;
    }

    UIDefaults uidefaults = UIManager.getDefaults();
    // if (uidefaults.contains(property)) {
    // NOTE: ok, UIDefaults object is strange. Not only does
    // it not implement the Map interface correctly, but entries
    // will not "stick". The entries must be first explicitly
    // removed, and then re-added - aaron
    log.debug("Removing UIDefaults key before overwriting: " + uikey);
    uidefaults.remove(uikey);
    // }

    if (Color.class.isAssignableFrom(type)) {
        uidefaults.put(uikey, new ColorUIResource((Color) decoded));
    } else {
        uidefaults.put(uikey, new FontUIResource((Font) decoded));
    }
}

From source file:org.deegree.services.wps.provider.jrxml.contentprovider.map.MapContentProvider.java

private Object prepareLegend(String legendKey, XMLAdapter jrxmlAdapter, List<OrderedDatasource<?>> datasources,
        String type, int resolution) throws ProcessletException {

    if ("net.sf.jasperreports.engine.JRRenderable".equals(type)) {
        return new LegendRenderable(datasources, resolution);
    } else {/* w w  w.j  ava2  s  .co  m*/
        OMElement legendRE = jrxmlAdapter.getElement(jrxmlAdapter.getRootElement(), new XPath(
                ".//jasper:image[jasper:imageExpression/text()='$P{" + legendKey + "}']/jasper:reportElement",
                nsContext));

        if (legendRE != null) {
            LOG.debug("Found legend with key '" + legendKey + "'.");
            int width = jrxmlAdapter.getRequiredNodeAsInteger(legendRE, new XPath("@width", nsContext));
            int height = jrxmlAdapter.getRequiredNodeAsInteger(legendRE, new XPath("@height", nsContext));
            width = adjustSpan(width, resolution);
            height = adjustSpan(height, resolution);

            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = bi.createGraphics();
            // TODO: bgcolor?
            Color bg = Color.decode("0xFFFFFF");
            g.setColor(bg);
            g.fillRect(0, 0, width, height);
            g.setColor(Color.BLACK);
            int k = 0;

            for (int i = 0; i < datasources.size(); i++) {
                if (k > height) {
                    LOG.warn("The necessary legend size is larger than the available legend space.");
                }
                List<Pair<String, BufferedImage>> legends = datasources.get(i).getLegends(width);
                for (Pair<String, BufferedImage> legend : legends) {
                    BufferedImage img = legend.second;
                    if (img != null) {
                        if (img.getWidth(null) < 50) {
                            // it is assumed that no label is assigned
                            g.drawImage(img, 0, k, null);
                            g.drawString(legend.first, img.getWidth(null) + 10, k + img.getHeight(null) / 2);
                        } else {
                            g.drawImage(img, 0, k, null);
                        }
                        k = k + img.getHeight(null) + 10;
                    } else {
                        g.drawString("- " + legend.first, 0, k + 10);
                        k = k + 20;
                    }
                }
            }
            g.dispose();
            return convertImageToReportFormat(type, bi);
        }
    }
    return null;
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

/**
 * Internal implementation to add a sunburst chart (actually a doughnut chart) to a slide, based on a template.
 * @param template the parsed template information.
 * @param slide the slide to add to.//from   w  ww.ja v  a 2 s . com
 * @param anchor optional bounding rectangle to draw onto, in PowerPoint coordinates.
 *               If null, we'll use the bounds from the original template chart.
 * @param data the sunburst data.
 * @param shapeId the slide shape ID, should be unique within the slide.
 * @param relId the relation ID to the chart data.
 * @throws TemplateLoadException if we can't create the sunburst; most likely due to an invalid template.
 */
private static void addSunburst(final SlideShowTemplate template, final XSLFSlide slide,
        final Rectangle2D.Double anchor, final SunburstData data, final int shapeId, final String relId)
        throws TemplateLoadException {
    final String[] categories = data.getCategories();
    final double[] values = data.getValues();
    final String title = data.getTitle();

    slide.getXmlObject().getCSld().getSpTree().addNewGraphicFrame()
            .set(template.getDoughnutChartShapeXML(relId, shapeId, "chart" + shapeId, anchor));

    final XSSFWorkbook workbook = new XSSFWorkbook();
    final XSSFSheet sheet = workbook.createSheet();

    final XSLFChart baseChart = template.getDoughnutChart();

    final CTChartSpace chartSpace = (CTChartSpace) baseChart.getCTChartSpace().copy();
    final CTChart ctChart = chartSpace.getChart();
    final CTPlotArea plotArea = ctChart.getPlotArea();

    if (StringUtils.isEmpty(title)) {
        if (ctChart.getAutoTitleDeleted() != null) {
            ctChart.getAutoTitleDeleted().setVal(true);
        }

        ctChart.unsetTitle();
    }

    final CTDoughnutChart donutChart = plotArea.getDoughnutChartArray(0);

    final CTPieSer series = donutChart.getSerArray(0);

    final CTStrRef strRef = series.getTx().getStrRef();
    strRef.getStrCache().getPtArray(0).setV(title);
    sheet.createRow(0).createCell(1).setCellValue(title);
    strRef.setF(new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString());

    final CTStrRef categoryRef = series.getCat().getStrRef();
    final CTStrData categoryData = categoryRef.getStrCache();
    final CTNumRef numRef = series.getVal().getNumRef();
    final CTNumData numericData = numRef.getNumCache();

    final String[] fillColors = data.getColors();
    final String[] strokeColors = data.getStrokeColors();
    final boolean overrideFill = ArrayUtils.isNotEmpty(fillColors);
    final boolean overrideStroke = ArrayUtils.isNotEmpty(strokeColors);
    final boolean overrideColors = overrideFill || overrideStroke;
    final List<CTDPt> dPtList = series.getDPtList();
    final CTDPt templatePt = (CTDPt) dPtList.get(0).copy();
    if (overrideColors) {
        dPtList.clear();

        final CTShapeProperties spPr = templatePt.getSpPr();
        final CTLineProperties ln = spPr.getLn();

        // We need to unset any styles on the existing template
        if (overrideFill) {
            unsetSpPrFills(spPr);
        }

        if (overrideStroke) {
            unsetLineFills(ln);
        }
    }

    categoryData.setPtArray(null);
    numericData.setPtArray(null);

    CTLegend legend = null;
    final int[] showInLegend = data.getShowInLegend();
    int nextLegendToShow = 0, nextLegendToShowIdx = -1;
    if (showInLegend != null) {
        // We need to write legendEntry elements to hide the legend for chart series we don't want.
        // Note this only works in PowerPoint, and not OpenOffice.
        legend = ctChart.isSetLegend() ? ctChart.getLegend() : ctChart.addNewLegend();
        Arrays.sort(showInLegend);
        nextLegendToShow = showInLegend[++nextLegendToShowIdx];
    }

    for (int idx = 0; idx < values.length; ++idx) {
        final CTStrVal categoryPoint = categoryData.addNewPt();
        categoryPoint.setIdx(idx);
        categoryPoint.setV(categories[idx]);

        final CTNumVal numericPoint = numericData.addNewPt();
        numericPoint.setIdx(idx);
        numericPoint.setV(Double.toString(values[idx]));

        if (overrideColors) {
            final CTDPt copiedPt = (CTDPt) templatePt.copy();
            copiedPt.getIdx().setVal(idx);

            if (overrideFill) {
                final Color color = Color.decode(fillColors[idx % fillColors.length]);
                final CTSolidColorFillProperties fillClr = copiedPt.getSpPr().addNewSolidFill();
                fillClr.addNewSrgbClr().setVal(
                        new byte[] { (byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue() });
            }

            if (overrideStroke) {
                final Color strokeColor = Color.decode(strokeColors[idx % strokeColors.length]);
                final CTSolidColorFillProperties strokeClr = copiedPt.getSpPr().getLn().addNewSolidFill();
                strokeClr.addNewSrgbClr().setVal(new byte[] { (byte) strokeColor.getRed(),
                        (byte) strokeColor.getGreen(), (byte) strokeColor.getBlue() });
            }

            dPtList.add(copiedPt);
        }

        if (legend != null) {
            // We're hiding some legend elements. Should we show this index?
            if (nextLegendToShow == idx) {
                // We show this index, find the next one to show.
                ++nextLegendToShowIdx;
                if (nextLegendToShowIdx < showInLegend.length) {
                    nextLegendToShow = showInLegend[nextLegendToShowIdx];
                }
            } else {
                // We hide this index. If there's already a matching legend entry in the XML, update it,
                //   otherwise we create a new legend entry.
                boolean found = false;
                for (int ii = 0, max = legend.sizeOfLegendEntryArray(); ii < max; ++ii) {
                    final CTLegendEntry legendEntry = legend.getLegendEntryArray(ii);
                    final CTUnsignedInt idxLegend = legendEntry.getIdx();
                    if (idxLegend != null && idxLegend.getVal() == idx) {
                        found = true;
                        if (legendEntry.isSetDelete()) {
                            legendEntry.getDelete().setVal(true);
                        } else {
                            legendEntry.addNewDelete().setVal(true);
                        }
                    }
                }

                if (!found) {
                    final CTLegendEntry idxLegend = legend.addNewLegendEntry();
                    idxLegend.addNewIdx().setVal(idx);
                    idxLegend.addNewDelete().setVal(true);
                }
            }
        }

        XSSFRow row = sheet.createRow(idx + 1);
        row.createCell(0).setCellValue(categories[idx]);
        row.createCell(1).setCellValue(values[idx]);
    }
    categoryData.getPtCount().setVal(categories.length);
    numericData.getPtCount().setVal(values.length);

    categoryRef.setF(new CellRangeAddress(1, values.length, 0, 0).formatAsString(sheet.getSheetName(), true));
    numRef.setF(new CellRangeAddress(1, values.length, 1, 1).formatAsString(sheet.getSheetName(), true));

    try {
        writeChart(template.getSlideShow(), slide, baseChart, chartSpace, workbook, relId);
    } catch (IOException | InvalidFormatException e) {
        throw new TemplateLoadException("Error writing chart in loaded template", e);
    }
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.BarCharts.java

/**
 * Calculates chart value;//w w w  .j  av  a2  s.  c  o m
 * 
 * 
 * public Dataset calculateValue(String cat, Map parameters) throws Exception {
 * logger.debug("IN");
 * String res=DataSetAccessFunctions.getDataSetResult(profile, getData(),parameters);
 * 
 * DefaultCategoryDataset dataset = new DefaultCategoryDataset();
 * 
 * SourceBean sbRows=SourceBean.fromXMLString(res);
 * List listAtts=sbRows.getAttributeAsList("ROW");
 * 
 * 
 * // run all categories (one for each row)
 * categoriesNumber=0;
 * for (Iterator iterator = listAtts.iterator(); iterator.hasNext();) {
 * SourceBean category = (SourceBean) iterator.next();
 * List atts=category.getContainedAttributes();
 * 
 * HashMap series=new HashMap();
 * String catValue="";
 * 
 * String name="";
 * String value="";
 * 
 * //run all the attributes, to define series!
 * for (Iterator iterator2 = atts.iterator(); iterator2.hasNext();) {
 * SourceBeanAttribute object = (SourceBeanAttribute) iterator2.next();
 * 
 * name=new String(object.getKey());
 * value=new String((String)object.getValue());
 * if(name.equalsIgnoreCase("x"))catValue=value;
 * else series.put(name, value);
 * }
 * for (Iterator iterator3 = series.keySet().iterator(); iterator3.hasNext();) {
 * String nameS = (String) iterator3.next();
 * String valueS=(String)series.get(nameS);
 * dataset.addValue(Double.valueOf(valueS).doubleValue(), nameS, catValue);
 * categoriesNumber=categoriesNumber+1;
 * }
 * 
 * }
 * logger.debug("OUT");
 * return dataset;
 * }
 * 
 * @param content the content
 */

public void configureChart(SourceBean content) {
    logger.debug("IN");
    super.configureChart(content);
    confParameters = new HashMap();
    SourceBean confSB = (SourceBean) content.getAttribute("CONF");

    if (confSB == null)
        return;
    List confAttrsList = confSB.getAttributeAsList("PARAMETER");

    Iterator confAttrsIter = confAttrsList.iterator();
    while (confAttrsIter.hasNext()) {
        SourceBean param = (SourceBean) confAttrsIter.next();
        String nameParam = (String) param.getAttribute("name");
        String valueParam = (String) param.getAttribute("value");
        confParameters.put(nameParam, valueParam);
    }

    if (confParameters.get("category_label") != null) {
        categoryLabel = (String) confParameters.get("category_label");
    } else {
        //categoryLabel="category";
        categoryLabel = "";
    }

    if (confParameters.get(VALUE_LABEL) != null) {
        valueLabel = (String) confParameters.get(VALUE_LABEL);
        String tmpValueLabel = valueLabel;
        while (!tmpValueLabel.equals("")) {
            if (tmpValueLabel.indexOf("$P{") >= 0) {
                String parName = tmpValueLabel.substring(tmpValueLabel.indexOf("$P{") + 3,
                        tmpValueLabel.indexOf("}"));

                String parValue = (parametersObject.get(parName) == null) ? ""
                        : (String) parametersObject.get(parName);
                parValue = parValue.replaceAll("\'", "");

                if (parValue.equals("%"))
                    parValue = "";
                int pos = tmpValueLabel.indexOf("$P{" + parName + "}") + (parName.length() + 4);
                valueLabel = valueLabel.replace("$P{" + parName + "}", parValue);
                tmpValueLabel = tmpValueLabel.substring(pos);
            } else
                tmpValueLabel = "";
        }
        setValueLabel(valueLabel);
    } else {
        //valueLabel="values";
        setValueLabel("");
    }

    if (confParameters.get(N_CAT_VISUALIZATION) != null || confParameters.get(N_VISUALIZATION) != null) {
        String nu = (String) confParameters.get(N_VISUALIZATION);
        if (nu == null)
            nu = (String) confParameters.get(N_CAT_VISUALIZATION);
        numberCatVisualization = Integer.valueOf(nu);
    } else {
        numberCatVisualization = new Integer(1);
    }

    dynamicNumberCatVisualization = false;
    if (confParameters.get(DYNAMIC_N_VISUALIZATION) != null) {
        String dynamicS = (String) confParameters.get(DYNAMIC_N_VISUALIZATION);
        if (dynamicS.equalsIgnoreCase("true"))
            dynamicNumberCatVisualization = true;
    }

    if (confParameters.get(N_SER_VISUALIZATION) != null) {
        String nu = (String) confParameters.get(N_SER_VISUALIZATION);
        numberSerVisualization = Integer.valueOf(nu);
    } else {
        numberSerVisualization = new Integer(0);
    }

    if (confParameters.get(FILTER_CAT_GROUPS) != null) {
        String filterCatGroupsS = (String) confParameters.get(FILTER_CAT_GROUPS);
        if (filterCatGroupsS.equalsIgnoreCase("false"))
            filterCatGroups = false;
        else
            filterCatGroups = true;
    } else {
        filterCatGroups = true;
    }

    if (confParameters.get(FILTER_SERIES) != null) {
        String filterSeriesS = (String) confParameters.get(FILTER_SERIES);
        if (filterSeriesS.equalsIgnoreCase("false"))
            filterSeries = false;
        else
            filterSeries = true;
    } else {
        filterSeries = true;
    }

    if (confParameters.get(FILTER_SERIES_BUTTONS) != null) {
        String filterSeriesS = (String) confParameters.get(FILTER_SERIES_BUTTONS);
        if (filterSeriesS.equalsIgnoreCase("false"))
            filterSeriesButtons = false;
    }

    if (confParameters.get(FILTER_CATEGORIES) != null) {
        String filterCategoriesS = (String) confParameters.get(FILTER_CATEGORIES);
        if (filterCategoriesS.equalsIgnoreCase("false"))
            filterCategories = false;
        else
            filterCategories = true;
    } else {
        filterCategories = true;
    }

    if (confParameters.get(SHOW_VALUE_LABLES) != null) {
        String valueLabelsS = (String) confParameters.get(SHOW_VALUE_LABLES);
        if (valueLabelsS.equalsIgnoreCase("true"))
            showValueLabels = true;
    }

    valueLabelsPosition = "inside";
    if (confParameters.get(VALUE_LABELS_POSITION) != null) {
        String valueLabelpos = (String) confParameters.get(VALUE_LABELS_POSITION);
        if (valueLabelpos.equalsIgnoreCase("outside"))
            valueLabelsPosition = "outside";
    }

    if (confParameters.get(ENABLE_TOOLTIPS) != null) {
        String enableTooltipsS = (String) confParameters.get(ENABLE_TOOLTIPS);
        if (enableTooltipsS.equalsIgnoreCase("true"))
            enableToolTips = true;
    }

    if (confParameters.get(MAXIMUM_BAR_WIDTH) != null) {
        String maxBarWidthS = (String) confParameters.get(MAXIMUM_BAR_WIDTH);
        try {
            maxBarWidth = Double.valueOf(maxBarWidthS);
        } catch (NumberFormatException e) {
            logger.error("error in defining parameter " + MAXIMUM_BAR_WIDTH
                    + ": should be a double, it will be ignored", e);
        }
    }

    if (confParameters.get(RANGE_INTEGER_VALUES) != null) {
        String rangeIntegerValuesS = (String) confParameters.get(RANGE_INTEGER_VALUES);
        if (rangeIntegerValuesS.equalsIgnoreCase("true"))
            rangeIntegerValues = true;
    }

    if (confParameters.get(RANGE_AXIS_LOCATION) != null) {
        //BOTTOM_OR_LEFT, BOTTOM_OR_RIGHT, TOP_OR_RIGHT, TOP_OR_LEFT
        String axisLocation = (String) confParameters.get(RANGE_AXIS_LOCATION);
        if (axisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT") || axisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")
                || axisLocation.equalsIgnoreCase("TOP_OR_LEFT")
                || axisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) {
            rangeAxisLocation = axisLocation;
        } else {
            logger.warn("Range Axis location specified: " + axisLocation + " not a valid value.");
        }
    }

    if (confParameters.get(FIRST_AXIS_LB) != null) {
        String axis = confParameters.get(FIRST_AXIS_LB).toString();
        Integer axisInte = Integer.valueOf(axis);
        firstAxisLB = axisInte;
    }

    if (confParameters.get(FIRST_AXIS_UB) != null) {
        String axis = confParameters.get(FIRST_AXIS_UB).toString();
        Integer axisInte = Integer.valueOf(axis);
        firstAxisUB = axisInte;
    }

    if (confParameters.get(SECOND_AXIS_LB) != null) {
        String axis = confParameters.get(SECOND_AXIS_LB).toString();
        Integer axisInte = Integer.valueOf(axis);
        secondAxisLB = axisInte;
    }

    if (confParameters.get(SECOND_AXIS_UB) != null) {
        String axis = confParameters.get(SECOND_AXIS_UB).toString();
        Integer axisInte = Integer.valueOf(axis);
        secondAxisUB = axisInte;
    }

    //reading series colors if present
    SourceBean colors = (SourceBean) content.getAttribute(SERIES_COLORS);
    if (colors == null) {
        colors = (SourceBean) content.getAttribute("CONF.SERIES_COLORS");
    }
    if (colors != null) {
        colorMap = new HashMap();
        List atts = colors.getContainedAttributes();
        String colorNum = "";
        String colorSerie = "";
        String num = "";
        for (Iterator iterator = atts.iterator(); iterator.hasNext();) {
            SourceBeanAttribute object = (SourceBeanAttribute) iterator.next();

            String serieName = new String(object.getKey());
            colorSerie = new String((String) object.getValue());
            Color col = new Color(Integer.decode(colorSerie).intValue());
            if (col != null) {
                colorMap.put(serieName, col);
            }
        }

    }

    //reading series colors if present, if present this overrides series colors!!!
    SourceBean orderColors = (SourceBean) content.getAttribute(SERIES_ORDER_COLORS);
    if (orderColors == null) {
        orderColors = (SourceBean) content.getAttribute("CONF." + SERIES_ORDER_COLORS);
    }
    if (orderColors != null) {
        orderColorVector = new Vector<Color>();
        List atts = orderColors.getContainedAttributes();
        String numSerie = "";
        String colorSerie = "";
        for (Iterator iterator = atts.iterator(); iterator.hasNext();) {
            SourceBeanAttribute object = (SourceBeanAttribute) iterator.next();
            numSerie = new String(object.getKey());
            colorSerie = new String((String) object.getValue());
            Color col = new Color(Integer.decode(colorSerie).intValue());
            if (col != null) {
                orderColorVector.add(col);
                //colorMap.put(numSerie,col); 
            }
        }

    }

    //reading filter style if present
    SourceBean sbSerieStyle = (SourceBean) content.getAttribute("STYLE_SLIDER_AREA");
    if (sbSerieStyle == null) {
        sbSerieStyle = (SourceBean) content.getAttribute("CONF.STYLE_SLIDER_AREA");
    }
    if (sbSerieStyle != null) {
        List atts = sbSerieStyle.getContainedAttributes();
        String StyleValue = "";
        for (Iterator iterator = atts.iterator(); iterator.hasNext();) {
            SourceBeanAttribute object = (SourceBeanAttribute) iterator.next();
            String styleLabel = (String) object.getKey();
            StyleValue = new String((String) object.getValue());
            if (StyleValue != null) {
                if (styleLabel.equalsIgnoreCase("font"))
                    styleLabel = "font-family";
                else if (styleLabel.equalsIgnoreCase("size"))
                    styleLabel = "font-size";
                else if (styleLabel.equalsIgnoreCase("color"))
                    styleLabel = "color";

                filterStyle += styleLabel + ":" + StyleValue + ";";
            }
        }
    }

    // check if there is some serie to be hidden
    boolean moreHiddenSeries = true;
    int i = 1;
    hiddenSeries = new Vector();
    while (moreHiddenSeries) {
        String iS = new Integer(i).toString();
        if (confParameters.get("hidden_serie" + iS) != null) {
            String hiddenSerName = (String) confParameters.get("hidden_serie" + iS);
            hiddenSeries.add(hiddenSerName);
            i++;
        } else
            moreHiddenSeries = false;

    }

    // check if there is some info about additional labels style

    SourceBean styleXaxisLabelsSB = (SourceBean) content.getAttribute("STYLE_X_AXIS_LABELS");
    if (styleXaxisLabelsSB != null) {

        String fontS = (String) content.getAttribute("STYLE_X_AXIS_LABELS.font");
        if (fontS == null) {
            fontS = defaultLabelsStyle.getFontName();
        }
        String sizeS = (String) content.getAttribute("STYLE_X_AXIS_LABELS.size");
        String colorS = (String) content.getAttribute("STYLE_X_AXIS_LABELS.color");
        String orientationS = (String) content.getAttribute("STYLE_X_AXIS_LABELS.orientation");
        if (orientationS == null) {
            orientationS = "horizontal";
        }

        try {
            Color color = Color.BLACK;
            if (colorS != null) {
                color = Color.decode(colorS);
            } else {
                defaultLabelsStyle.getColor();
            }
            int size = 12;
            if (sizeS != null) {
                size = Integer.valueOf(sizeS).intValue();
            } else {
                size = defaultLabelsStyle.getSize();
            }

            styleXaxesLabels = new StyleLabel(fontS, size, color);

        } catch (Exception e) {
            logger.error("Wrong style labels settings, use default");
        }

    } else {
        styleXaxesLabels = defaultLabelsStyle;
    }

    SourceBean styleYaxisLabelsSB = (SourceBean) content.getAttribute("STYLE_Y_AXIS_LABELS");
    if (styleYaxisLabelsSB != null) {

        String fontS = (String) content.getAttribute("STYLE_Y_AXIS_LABELS.font");
        if (fontS == null) {
            fontS = defaultLabelsStyle.getFontName();
        }
        String sizeS = (String) content.getAttribute("STYLE_Y_AXIS_LABELS.size");
        String colorS = (String) content.getAttribute("STYLE_Y_AXIS_LABELS.color");
        String orientationS = (String) content.getAttribute("STYLE_Y_AXIS_LABELS.orientation");
        if (orientationS == null) {
            orientationS = "horizontal";
        }

        try {
            Color color = Color.BLACK;
            if (colorS != null) {
                color = Color.decode(colorS);
            } else {
                defaultLabelsStyle.getColor();
            }
            int size = 12;
            if (sizeS != null) {
                size = Integer.valueOf(sizeS).intValue();
            } else {
                size = defaultLabelsStyle.getSize();
            }

            styleYaxesLabels = new StyleLabel(fontS, size, color);

        } catch (Exception e) {
            logger.error("Wrong style labels settings, use default");
        }

    } else {
        styleYaxesLabels = defaultLabelsStyle;
    }

    SourceBean styleValueLabelsSB = (SourceBean) content.getAttribute("STYLE_VALUE_LABELS");
    if (styleValueLabelsSB != null) {

        String fontS = (String) content.getAttribute("STYLE_VALUE_LABELS.font");
        if (fontS == null) {
            fontS = defaultLabelsStyle.getFontName();
        }
        String sizeS = (String) content.getAttribute("STYLE_VALUE_LABELS.size");
        String colorS = (String) content.getAttribute("STYLE_VALUE_LABELS.color");
        String orientationS = (String) content.getAttribute("STYLE_VALUE_LABELS.orientation");
        if (orientationS == null) {
            orientationS = "horizontal";
        }

        try {
            Color color = Color.BLACK;
            if (colorS != null) {
                color = Color.decode(colorS);
            } else {
                defaultLabelsStyle.getColor();
            }
            int size = 12;
            if (sizeS != null) {
                size = Integer.valueOf(sizeS).intValue();
            } else {
                size = defaultLabelsStyle.getSize();
            }

            styleValueLabels = new StyleLabel(fontS, size, color, orientationS);

        } catch (Exception e) {
            logger.error("Wrong style labels settings, use default");
        }

    } else {
        styleValueLabels = defaultLabelsStyle;
    }

    seriesNumber = new HashMap();

    logger.debug("OUT");
}

From source file:org.springframework.richclient.application.config.DefaultApplicationObjectConfigurer.java

/**
 * Attempts to load a {@link Color} by decoding the message that is found by
 * looking up the given colorKey. Decoding is done by by
 * {@link Color#decode(String)}./*  w w w  . j a  v a2s.co  m*/
 * 
 * @param colorKey The message code used to retrieve the colour code.
 * @return the decoded {@link Color} or <code>null</code> if no colour could
 * be decoded/found.
 */
private Color loadColor(String colorKey) {
    String colorCode = loadMessage(colorKey);
    if (colorCode == null) {
        return null;
    }
    try {
        return Color.decode(colorCode);
    } catch (NumberFormatException nfe) {
        if (logger.isWarnEnabled()) {
            logger.warn("Could not parse a valid Color from code [" + colorCode
                    + "]. Ignoring and returning null.");
        }
        return null;
    }
}

From source file:edu.jhuapl.openessence.web.util.ControllerUtils.java

/**
 * Parses hex encoded colors into java Color objects.
 *
 * @param color     a default Color if a hex color string fails to parse
 * @param hexColors an array of colors to parse
 * @return array of java.awt.Color objects from hex.
 *//*from   w ww.j a v a  2s  .  co  m*/
public static Color[] getColorsFromHex(Color color, String... hexColors) {
    Color[] colors = new Color[hexColors.length];
    for (int i = 0; i < hexColors.length; i++) {
        try {
            colors[i] = Color.decode(hexColors[i]);
        } catch (Exception e) {
            colors[i] = color;
        }
    }
    return colors;
}

From source file:com.zacwolf.commons.email.Email.java

public static Color getColorFromStyle(String style, Color defaultcolor) {
    if (!style.contains("#"))
        return defaultcolor;
    int hexcolorstarts = style.indexOf("#");
    if (hexcolorstarts == -1)
        return defaultcolor;
    int hexcolorends = style.indexOf(" ", hexcolorstarts);
    if (hexcolorends == -1)
        hexcolorends = style.indexOf(";", hexcolorstarts);
    if (hexcolorends == -1)
        hexcolorends = style.length();//from   www.  j  a v a2  s  .  co m
    try {
        return Color.decode(style.substring(hexcolorstarts, hexcolorends));
    } catch (Exception e) {
        //TODO
    }
    return defaultcolor;
}

From source file:org.rdv.ui.TimeSlider.java

/**
 * Creates the tooltip for the component. This changes the default tooltip by
 * setting a different border.//from   ww  w.  j a  va  2s .  c o m
 * 
 * @return  the tooltip created
 */
public JToolTip createToolTip() {
    JToolTip toolTip = super.createToolTip();
    toolTip.setBackground(Color.decode("#FFFFFC"));
    toolTip.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    return toolTip;
}

From source file:org.apache.myfaces.custom.roundeddiv.HtmlRoundedDivRenderer.java

/**
 * Build a set of parameters as a map that are needed for the rendering
 * //from  www. j ava 2s . c o m
 * @param component The component
 * @param area The area
 * @return Map of parameters
 */
protected Map buildParameterMap(HtmlRoundedDiv component, String area) {
    Map map = new HashMap(7);
    if (component.getColor() != null) {
        map.put("c", colorToHtml(Color.decode(component.getColor())));
    }
    Color c;
    if (component.getBackgroundColor() != null) {
        c = Color.decode(component.getBackgroundColor());
        map.put("bgc", colorToHtml(c));
    }
    if (component.getBorderColor() != null) {
        c = Color.decode(component.getBorderColor());
        map.put("bc", colorToHtml(c));
    }

    map.put("bw", component.getBorderWidth().toString());
    map.put("r", component.getRadius().toString());
    Dimension d;
    if (component.getSize() != null) {
        d = _getSize(component);
        map.put("s", d.width + "x" + d.height);
    }
    if (area != null) {
        map.put("a", area);
    }
    map.put("i", component.getInverse().booleanValue() ? "t" : "f");
    return map;
}

From source file:probe.com.view.body.quantdatasetsoverview.diseasegroupsfilters.ComparisonsSelectionOverviewBubbleChart.java

private JFreeChart updateBubbleChartChart(Set<QuantDiseaseGroupsComparison> selectedComparisonList) {

    if (userCustomizedComparison != null) {
        return updateBubbleChartChartWithCustUserData(selectedComparisonList);
    }/*  w w w. j  av a  2s .  c  o m*/
    tooltipsProtNumberMap.clear();
    DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset();
    int counter = 0;
    int upper = -1;
    boolean significantOnly = this.Quant_Central_Manager.isSignificantOnly();

    for (QuantDiseaseGroupsComparison qc : selectedComparisonList) {
        if (significantOnly) {
            int upperCounter = 0;
            for (DiseaseGroupsComparisonsProteinLayout qp : qc.getComparProtsMap().values()) {
                if (qp == null) {
                    continue;
                }

                if (qp.getSignificantTrindCategory() == 2 || qp.getSignificantTrindCategory() == 5) {
                    continue;
                }

                upperCounter++;
            }
            if (upperCounter > upper) {
                upper = upperCounter;
            }

        } else {
            if (qc.getComparProtsMap() == null) {
                System.out.println("null qc " + qc.getComparisonHeader());

            }
            if (qc.getComparProtsMap().size() > upper) {
                upper = qc.getComparProtsMap().size();
            }
        }

    }

    final Map<Integer, Color[]> seriousColorMap = new HashMap<Integer, Color[]>();
    Color[] dataColor = new Color[] { Color.WHITE, new Color(0, 153, 0), new Color(0, 229, 132), stableColor,
            new Color(247, 119, 119), new Color(204, 0, 0), Color.WHITE };

    double[] yAxisValueI = new double[] { 0, 0, 0, 0, 0, 0, 0 };
    double[] xAxisValueI = new double[] { 0, 0, 0, 0, 0, 0, 0 };
    double[] widthValueI = new double[] { 0, 0, 0, 0, 0, 0, 0 };
    double[][] seriesValuesI = { yAxisValueI, xAxisValueI, widthValueI };
    seriousColorMap.put(0, new Color[] { Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE,
            Color.WHITE, Color.WHITE });
    defaultxyzdataset.addSeries("   ", seriesValuesI);

    for (QuantDiseaseGroupsComparison qc : selectedComparisonList) {

        double[] tempWidthValue = new double[8];
        if (qc.getComparProtsMap() == null) {
            continue;
        }

        for (String key : qc.getComparProtsMap().keySet()) {
            qc.getComparProtsMap().get(key).updateLabelLayout();

            if (significantOnly && (qc.getComparProtsMap().get(key).getSignificantTrindCategory() == 2
                    || qc.getComparProtsMap().get(key).getSignificantTrindCategory() == 5)) {
                tempWidthValue[3] = 0;
                tempWidthValue[6] = 0;
            } else {
                tempWidthValue[qc.getComparProtsMap().get(key).getSignificantTrindCategory()
                        + 1] = tempWidthValue[qc.getComparProtsMap().get(key).getSignificantTrindCategory() + 1]
                                + 1;
            }
        }

        if (tempWidthValue[3] > 0 && tempWidthValue[3] >= 0) {
            stableColor = new Color(1, 141, 244);

        } else {
            stableColor = Color.decode("#b5babb");

        }

        tempWidthValue[3] = tempWidthValue[3] + tempWidthValue[6];
        tempWidthValue[6] = 0;
        dataColor[3] = stableColor;

        int length = 0;
        if (upper < 10) {
            upper = 10;
        }

        double[] tooltipNumbess = new double[tempWidthValue.length];
        System.arraycopy(tempWidthValue, 0, tooltipNumbess, 0, tempWidthValue.length);
        this.tooltipsProtNumberMap.put(qc.getComparisonHeader(), tooltipNumbess);
        for (int x = 0; x < tempWidthValue.length; x++) {
            if (tempWidthValue[x] > 0) {
                tempWidthValue[x] = scaleValues(tempWidthValue[x], upper, 2.5, 0.05);//Math.max(tempWidthValue[x] * 1.5 / upper, 0.05);
                length++;
            }

        }
        double[] yAxisValue = new double[length];
        double[] xAxisValue = new double[length];
        double[] widthValue = new double[length];
        Color[] serColorArr = new Color[length];
        length = 0;

        for (int x = 0; x < tempWidthValue.length; x++) {
            if (tempWidthValue[x] > 0) {
                xAxisValue[length] = x;
                yAxisValue[length] = counter + 1;
                widthValue[length] = tempWidthValue[x];
                serColorArr[length] = dataColor[x];
                length++;
            }

        }

        if (length == 1 && selectedComparisonList.size() == 1) {
            widthValue[0] = 1;
        }
        seriousColorMap.put(counter + 1, serColorArr);

        double[][] seriesValues = { yAxisValue, xAxisValue, widthValue };
        defaultxyzdataset.addSeries(qc.getComparisonHeader(), seriesValues);
        counter++;
    }
    double[] yAxisValueII = new double[0];
    double[] xAxisValueII = new double[0];
    double[] widthValueII = new double[0];
    seriousColorMap.put(counter + 1, new Color[] {});
    double[][] seriesValuesII = { yAxisValueII, xAxisValueII, widthValueII };
    defaultxyzdataset.addSeries(" ", seriesValuesII);

    final Color[] labelsColor = new Color[] { Color.LIGHT_GRAY, new Color(80, 183, 71), Color.LIGHT_GRAY,
            new Color(1, 141, 244), Color.LIGHT_GRAY, new Color(204, 0, 0), Color.LIGHT_GRAY };
    Font font = new Font("Verdana", Font.BOLD, 13);
    SymbolAxis yAxis = new SymbolAxis(null,
            new String[] { "  ", "Decreased", " ", "Equal", " ", "Increased", "  " }) {

        int i = 0;

        @Override
        public RectangleInsets getTickLabelInsets() {
            //                System.out.println("at ---- super.getTickLabelInsets() " + super.getTickLabelInsets());
            //                if (i == 0) {
            //                    i++;
            //                    return new RectangleInsets(-5, -5, 0, 0);
            //                }else                   
            //                
            return super.getTickLabelInsets(); //To change body of generated methods, choose Tools | Templates.
        }

        int x = 0;

        @Override
        public Paint getTickLabelPaint() {
            if (x >= labelsColor.length) {
                x = 0;
            }
            return labelsColor[x++];
        }
    };
    yAxis.setAutoRangeStickyZero(true);
    yAxis.setFixedAutoRange(8);
    yAxis.setTickLabelFont(font);
    yAxis.setGridBandsVisible(false);
    yAxis.setAxisLinePaint(Color.LIGHT_GRAY);
    yAxis.setTickMarksVisible(false);
    yAxis.setUpperBound(6);

    String[] xAxisLabels = new String[selectedComparisonList.size() + 2];
    int x = 0;
    xAxisLabels[x] = "";
    int maxLength = -1;
    //init labels color

    final Color[] diseaseGroupslabelsColor = new Color[selectedComparisonList.size() + 2];
    diseaseGroupslabelsColor[x] = Color.WHITE;
    x++;

    for (QuantDiseaseGroupsComparison comp : selectedComparisonList) {
        String header = comp.getComparisonHeader();
        String updatedHeader = header.split(" / ")[0].split("\n")[0] + " / "
                + header.split(" / ")[1].split("\n")[0] + "";

        xAxisLabels[x] = updatedHeader + " (" + comp.getDatasetIndexes().length + ")    ";
        if (xAxisLabels[x].length() > maxLength) {
            maxLength = xAxisLabels[x].length();
        }
        diseaseGroupslabelsColor[x] = diseaseColorMap.get(header.split(" / ")[0].split("\n")[1]);
        x++;

    }
    xAxisLabels[x] = "";
    diseaseGroupslabelsColor[x] = Color.WHITE;

    SymbolAxis xAxis;
    final boolean finalNum;
    finalNum = maxLength > 30 && selectedComparisonList.size() > 4;

    xAxis = new SymbolAxis(null, xAxisLabels) {

        int x = 0;

        @Override
        public Paint getTickLabelPaint() {
            if (x >= diseaseGroupslabelsColor.length) {
                x = 0;
            }
            return diseaseGroupslabelsColor[x++];
        }

        private final boolean localfinal = finalNum;

        @Override
        protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {

            if (localfinal) {
                setVerticalTickLabels(localfinal);
                return super.refreshTicksHorizontal(g2, dataArea, edge);
            }
            List ticks = new java.util.ArrayList();
            Font tickLabelFont = getTickLabelFont();
            g2.setFont(tickLabelFont);
            double size = getTickUnit().getSize();
            int count = calculateVisibleTickCount();
            double lowestTickValue = calculateLowestVisibleTickValue();
            double previousDrawnTickLabelPos = 0.0;
            double previousDrawnTickLabelLength = 0.0;
            if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
                for (int i = 0; i < count; i++) {
                    double currentTickValue = lowestTickValue + (i * size);
                    double xx = valueToJava2D(currentTickValue, dataArea, edge);
                    String tickLabel;
                    NumberFormat formatter = getNumberFormatOverride();
                    if (formatter != null) {
                        tickLabel = formatter.format(currentTickValue) + "  ";
                    } else {
                        tickLabel = valueToString(currentTickValue) + "  ";
                    }
                    // avoid to draw overlapping tick labels
                    Rectangle2D bounds = TextUtilities.getTextBounds(tickLabel, g2, g2.getFontMetrics());
                    double tickLabelLength = isVerticalTickLabels() ? bounds.getHeight() : bounds.getWidth();
                    boolean tickLabelsOverlapping = false;
                    if (i > 0) {
                        double avgTickLabelLength = (previousDrawnTickLabelLength + tickLabelLength) / 2.0;
                        if (Math.abs(xx - previousDrawnTickLabelPos) < avgTickLabelLength) {
                            tickLabelsOverlapping = true;
                        }
                    }
                    if (tickLabelsOverlapping) {
                        setVerticalTickLabels(true);
                    } else {
                        // remember these values for next comparison
                        previousDrawnTickLabelPos = xx;
                        previousDrawnTickLabelLength = tickLabelLength;
                    }
                    TextAnchor anchor;
                    TextAnchor rotationAnchor;
                    double angle = 0.0;
                    if (isVerticalTickLabels()) {
                        anchor = TextAnchor.CENTER_RIGHT;
                        rotationAnchor = TextAnchor.CENTER_RIGHT;
                        if (edge == RectangleEdge.TOP) {
                            angle = 76.5;
                        } else {
                            angle = -76.5;
                        }
                    } else {
                        if (edge == RectangleEdge.TOP) {
                            anchor = TextAnchor.BOTTOM_CENTER;
                            rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        } else {
                            anchor = TextAnchor.TOP_CENTER;
                            rotationAnchor = TextAnchor.TOP_CENTER;
                        }
                    }
                    Tick tick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor,
                            angle);

                    ticks.add(tick);
                }
            }
            return ticks;
        }
    };

    //        }
    xAxis.setTickLabelFont(font);
    xAxis.setTickLabelInsets(new RectangleInsets(2, 20, 2, 20));
    xAxis.setAutoRangeStickyZero(true);
    xAxis.setTickMarksVisible(false);
    xAxis.setUpperBound(diseaseGroupslabelsColor.length - 1);

    xAxis.setGridBandsVisible(false);
    xAxis.setAxisLinePaint(Color.LIGHT_GRAY);
    int scale = XYBubbleRenderer.SCALE_ON_RANGE_AXIS;

    XYItemRenderer xyitemrenderer = new XYBubbleRenderer(scale) {
        private int counter = 0;
        private int localSerious = -1;
        private final Map<Integer, Color[]> localSeriousColorMap = seriousColorMap;

        @Override
        public Paint getSeriesPaint(int series) {
            if (series != localSerious || isNewImge || localSeriousColorMap.get(series).length == counter) {
                counter = 0;
                isNewImge = false;
            }
            localSerious = series;
            Color c = localSeriousColorMap.get(series)[counter];
            counter++;

            return c;
        }

    };

    XYPlot xyplot = new XYPlot(defaultxyzdataset, xAxis, yAxis, xyitemrenderer) {

        @Override
        protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area, List ticks) {
            try {
                if (!ticks.isEmpty()) {
                    ticks.remove(0);
                }
                if (!ticks.isEmpty()) {
                    ticks.remove(ticks.size() - 1);
                }
            } catch (Exception e) {
            }
            super.drawRangeGridlines(g2, area, ticks); //To change body of generated methods, choose Tools | Templates.
        }

        //            private final Color[] labelsColor = new Color[]{new Color(0, 153, 0), new Color(0, 229, 132), new Color(1, 141, 244), new Color(255, 51, 51), new Color(204, 0, 0), Color.decode("#b5babb")};
        //
        //            private final Font font = new Font("Verdana", Font.PLAIN, 12);
        //            private final String[] labels = new String[]{"Decreased 100%", "Decreased <100% ", "Equal", " Increased <100%", "Increased 100%", "No Quant. Info."};
        //
        //            @Override
        //            public LegendItemCollection getLegendItems() {
        //                LegendItemCollection legendItemCollection = new LegendItemCollection();
        //                for (int i = 0; i < labelsColor.length; i++) {
        //                    LegendItem item = new LegendItem(labels[i], labelsColor[i]);
        //                    item.setLabelFont(font);
        //
        //                    legendItemCollection.add(item);
        //
        //                }
        //
        //                return legendItemCollection;//To change body of generated methods, choose Tools | Templates.
        //            }
    };

    JFreeChart generatedChart = new JFreeChart(xyplot) {

    };

    xyplot.setOutlineVisible(false);
    LegendTitle legend = generatedChart.getLegend();

    legend.setVisible(false);
    //        legend.setMargin(20, 0, 0, 0);
    ////        legend.setBorder(1, 1, 1, 1);
    //        legend.setFrame(new BlockBorder(1, 0, 1, 0, Color.LIGHT_GRAY));

    //        generatedChart.removeLegend();
    //        xyplot.setForegroundAlpha(0.65F);
    xyplot.setBackgroundPaint(Color.WHITE);

    generatedChart.setBackgroundPaint(Color.WHITE);

    generatedChart.setPadding(new RectangleInsets(0, 0, 0, 0));
    Quant_Central_Manager.setProteinsOverviewBubbleChart(generatedChart);
    //        exporter.writeChartToPDFFile(generatedChart, 595, 842, "bublechart.pdf");
    return generatedChart;

}