Example usage for org.jfree.chart.title TextTitle getFont

List of usage examples for org.jfree.chart.title TextTitle getFont

Introduction

In this page you can find the example usage for org.jfree.chart.title TextTitle getFont.

Prototype

public Font getFont() 

Source Link

Document

Returns the font used to display the title string.

Usage

From source file:com.globalsight.util.JfreeCharUtil.java

public static void drawPieChart2D(String title, Map<String, Double> datas, File OutFile) {
    PieDataset dataset = buildDatas(datas);
    JFreeChart chart = ChartFactory.createPieChart(title, dataset, true, true, false);
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})",
            NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
    chart.setBackgroundPaint(Color.white);
    plot.setCircular(true);/*from   w w  w .j ava 2 s .  c  o  m*/
    TextTitle textTitle = new TextTitle(title);
    Font font = new Font(textTitle.getFont().getName(), Font.CENTER_BASELINE, 20);
    textTitle.setFont(font);
    chart.setTitle(textTitle);
    FileOutputStream fos_jpg = null;

    try {
        fos_jpg = new FileOutputStream(OutFile);
        ChartUtilities.writeChartAsJPEG(fos_jpg, 1, chart, 640, 480, null);
        fos_jpg.close();
    } catch (Exception e) {
        s_logger.error(e.getMessage(), e);
    }
}

From source file:com.globalsight.util.JfreeCharUtil.java

public static void drawPieChart3D(String title, Map<String, Double> datas, File OutFile) {
    PieDataset dataset = buildDatas(datas);
    JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);
    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})",
            NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
    chart.setBackgroundPaint(Color.white);
    plot.setForegroundAlpha(0.7f);//ww w .j  av  a2  s .  c  om
    plot.setCircular(true);
    TextTitle textTitle = new TextTitle(title);
    Font font = new Font(textTitle.getFont().getName(), Font.CENTER_BASELINE, 20);
    textTitle.setFont(font);
    chart.setTitle(textTitle);
    FileOutputStream fos_jpg = null;

    try {
        fos_jpg = new FileOutputStream(OutFile);
        ChartUtilities.writeChartAsJPEG(fos_jpg, 1, chart, 640, 480, null);
        fos_jpg.close();
    } catch (Exception e) {
        s_logger.error(e.getMessage(), e);
    }
}

From source file:cz.muni.fi.nbs.utils.Helpers.java

private static void exportToPNG(Map<String, Collection<Result>> results) {

    for (Entry<String, Collection<Result>> entry : results.entrySet()) {
        double number = 0;
        String key = entry.getKey();
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        Iterator<Result> resultsIterator = results.get(key).iterator();
        while (resultsIterator.hasNext()) {
            Result r = resultsIterator.next();
            dataset.addValue(r.getScore(), r.getLabel(), "");
            number += 0.8;// www .j  a  va2s  .c  o m
        }
        double width = number > 1 ? number * 200 : 300;
        String unit = entry.getValue().iterator().next().getScoreUnit();
        String[] splitKey = key.split("_");

        JFreeChart chart = ChartFactory.createBarChart3D(splitKey[0], null, unit, dataset);

        int len = splitKey.length / 2;
        for (int i = 0; i < len; i++) {
            String subtitle = splitKey[i * 2 + 1] + ":" + splitKey[i * 2 + 2];
            TextTitle title = new TextTitle(subtitle);
            Font oldFont = title.getFont();
            int fontSize = (int) Math.round(oldFont.getSize() * 1.2);
            int fontStyle = oldFont.getStyle();
            String fontName = oldFont.getName();

            title.setFont(new Font(fontName, fontStyle, fontSize));
            chart.addSubtitle(title);
        }
        try {
            ChartUtilities.saveChartAsPNG(new File(resultsDir + "/charts/" + key + "Chart.png"), chart,
                    (int) Math.round(width), 800);
        } catch (IOException ex) {
            Logger.getLogger(Helpers.class.getName()).log(Level.SEVERE,
                    "Could not export chart to PNG file for " + key, ex);
        }
    }
}

From source file:daylightchart.options.chart.TitleOptions.java

/**
 * {@inheritDoc}/*from   w  w w  .  j a v  a2s.  com*/
 *
 * @see BaseChartOptions#copyFromChart(org.jfree.chart.JFreeChart)
 */
@Override
public void copyFromChart(final JFreeChart chart) {
    final TextTitle title = chart.getTitle();
    if (title != null) {
        titleFont = title.getFont();
        titlePaint = title.getPaint();
        titleText = title.getText();
    }
}

From source file:daylightchart.daylightchart.chart.DaylightChart.java

/**
 * {@inheritDoc}/*from   w w  w . ja  va  2 s .co m*/
 *
 * @see daylightchart.options.chart.ChartOptionsListener#afterSettingChartOptions(ChartOptions)
 */
@Override
public void afterSettingChartOptions(final ChartOptions chartOptions) {
    Font titleFont;
    final TextTitle title = getTitle();
    if (title != null) {
        titleFont = title.getFont();
    } else {
        titleFont = ChartConfiguration.chartFont;
    }
    createTitles(chartOptions, titleFont.deriveFont(Font.BOLD, 18));
}

From source file:nl.strohalm.cyclos.controls.reports.statistics.graphs.ChartPostProcessorImpl.java

/**
 * This method renders a subtitle above the graph, in case the subtitle string is not null or "". Set the subTitle in the jsp via the param tag,
 * using the keyword "subtitle": <cewolf:chartpostprocessor id="chartPostProcessorImpl" > <cewolf:param name="subtitle"
 * value="${dataTable.subTitle}"/> </cewolf:chartpostprocessor>
 * @param chart/*from   ww w  .  j  a va 2s.co m*/
 * @param params
 */
@SuppressWarnings("rawtypes")
private void setSubTitle(final Object chart, final Map params) {
    final String subtitleString = (String) params.get("subtitle");
    if (subtitleString != null && subtitleString.trim().length() > 0) {
        final TextTitle subtitle = new TextTitle(subtitleString);
        subtitle.setFont(subtitle.getFont().deriveFont(11f)); // TODO font size may be parameterized later on???
        ((JFreeChart) chart).addSubtitle(subtitle);
    }
}

From source file:net.sf.dynamicreports.test.jasper.chart.ChartTest.java

@Override
public void test() {
    super.test();

    numberOfPagesTest(1);/*from w  w w.  ja  v  a  2 s .  c  om*/

    chartCountTest("summary.chart1", 1);
    JFreeChart chart = getChart("summary.chart1", 0);

    TextTitle title = chart.getTitle();
    Assert.assertEquals("title", "title", title.getText());
    Assert.assertEquals("title color", Color.BLUE, title.getPaint());
    Assert.assertEquals("title font", new Font("Arial", Font.BOLD, 10), title.getFont());
    Assert.assertEquals("title position", RectangleEdge.RIGHT, title.getPosition());

    TextTitle subtitle = (TextTitle) chart.getSubtitle(1);
    Assert.assertEquals("subtitle", "subtitle", subtitle.getText());
    Assert.assertEquals("subtitle color", Color.CYAN, subtitle.getPaint());
    Assert.assertEquals("subtitle font", new Font("Arial", Font.PLAIN, 10), subtitle.getFont());

    LegendTitle legend = (LegendTitle) chart.getSubtitle(0);
    Assert.assertEquals("legend color", Color.BLUE, legend.getItemPaint());
    Assert.assertEquals("legend backgroundcolor", Color.LIGHT_GRAY, legend.getBackgroundPaint());
    Assert.assertEquals("legend font", new Font("Courier New", Font.PLAIN, 10), legend.getItemFont());
    Assert.assertEquals("legend position", RectangleEdge.LEFT, legend.getPosition());

    chartCountTest("summary.chart2", 1);
    chart = getChart("summary.chart2", 0);
    Assert.assertNull("legend", chart.getLegend());
    Assert.assertEquals("plot orientation", PlotOrientation.HORIZONTAL,
            chart.getCategoryPlot().getOrientation());
    Assert.assertEquals("plot series colors", Color.BLUE, chart.getPlot().getDrawingSupplier().getNextPaint());
    Assert.assertEquals("plot series colors", Color.GREEN, chart.getPlot().getDrawingSupplier().getNextPaint());
    Assert.assertEquals("plot series colors", Color.RED, chart.getPlot().getDrawingSupplier().getNextPaint());
}

From source file:ch.zhaw.simulation.diagram.charteditor.DefaultTitleEditor.java

/**
 * Standard constructor: builds a panel for displaying/editing the
 * properties of the specified title./*from   w  w w  .  j a  va 2s .c  o m*/
 * 
 * @param title
 *            the title, which should be changed.
 */
public DefaultTitleEditor(Title title) {
    if (title == null) {
        this.showTitle = false;
        this.titleFont = SimulationDiagramTheme.DEFAULT_TITLE_FONT;
        this.titleField = new JTextField();
        this.titlePaint = new PaintSample(Color.BLACK);

    } else {
        TextTitle t = (TextTitle) title;

        this.showTitle = title.isVisible();
        this.titleFont = t.getFont();
        this.titleField = new JTextField(t.getText());
        this.titlePaint = new PaintSample(t.getPaint());
    }

    System.out.println(this.titleFont.getName());

    setLayout(new BorderLayout());

    JPanel general = new JPanel(new BorderLayout());
    general.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
            localizationResources.getString("General")));

    JPanel interior = new JPanel(new LCBLayout(4));
    interior.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

    interior.add(new JLabel(localizationResources.getString("Show_Title")));
    this.showTitleCheckBox = new JCheckBox();
    this.showTitleCheckBox.setSelected(this.showTitle);
    this.showTitleCheckBox.setActionCommand("ShowTitle");
    this.showTitleCheckBox.addActionListener(this);
    interior.add(new JPanel());
    interior.add(this.showTitleCheckBox);

    JLabel titleLabel = new JLabel(localizationResources.getString("Text"));
    interior.add(titleLabel);
    interior.add(this.titleField);
    interior.add(new JPanel());

    JLabel fontLabel = new JLabel(localizationResources.getString("Font"));
    this.fontfield = new FontDisplayField(this.titleFont);
    this.selectFontButton = new JButton(localizationResources.getString("Select..."));
    this.selectFontButton.setActionCommand("SelectFont");
    this.selectFontButton.addActionListener(this);
    interior.add(fontLabel);
    interior.add(this.fontfield);
    interior.add(this.selectFontButton);

    JLabel colorLabel = new JLabel(localizationResources.getString("Color"));
    this.selectPaintButton = new JButton(localizationResources.getString("Select..."));
    this.selectPaintButton.setActionCommand("SelectPaint");
    this.selectPaintButton.addActionListener(this);
    interior.add(colorLabel);
    interior.add(this.titlePaint);
    interior.add(this.selectPaintButton);

    this.enableOrDisableControls();

    general.add(interior);
    add(general, BorderLayout.NORTH);
}

From source file:playground.thibautd.analysis.joinabletripsidentifier.DataPloter.java

private void formatChart(final JFreeChart chart) {
    TextTitle title = chart.getTitle();
    Font font = title.getFont();
    title.setFont(font.deriveFont(TITLE_FONT_SIZE));
    chart.getPlot().setBackgroundPaint(new Color(1.0f, 1.0f, 1.0f, 1.0f));
}

From source file:nu.nethome.home.items.web.GraphServlet.java

/**
* This is the main enterence point of the class. This is called when a http request is
* routed to this servlet.//w ww .j av  a2 s .  co m
*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServletOutputStream p = res.getOutputStream();
    Date startTime = null;
    Date stopTime = null;

    // Analyse arguments
    String fileName = req.getParameter("file");
    if (fileName != null)
        fileName = getFullFileName(fromURL(fileName));
    String startTimeString = req.getParameter("start");
    String stopTimeString = req.getParameter("stop");
    try {
        if (startTimeString != null) {
            startTime = m_Format.parse(startTimeString);
        }
        if (stopTimeString != null) {
            stopTime = m_Format.parse(stopTimeString);
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    String look = req.getParameter("look");
    if (look == null)
        look = "";

    TimeSeries timeSeries = new TimeSeries("Data", Minute.class);

    // Calculate time window
    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date startOfDay = cal.getTime();
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    Date startOfWeek = cal.getTime();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    Date startOfMonth = cal.getTime();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    Date startOfYear = cal.getTime();

    // if (startTime == null) startTime = startOfWeek;
    if (stopTime == null)
        stopTime = currentTime;
    if (startTime == null)
        startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L);

    try {
        // Open the data file
        File logFile = new File(fileName);
        Scanner fileScanner = new Scanner(logFile);
        Long startTimeMs = startTime.getTime();
        Long month = 1000L * 60L * 60L * 24L * 30L;
        boolean doOptimize = true;
        boolean justOptimized = false;
        try {
            while (fileScanner.hasNext()) {
                try {
                    // Get next log entry
                    String line = fileScanner.nextLine();
                    if (line.length() > 21) {
                        // Adapt the time format
                        String minuteTime = line.substring(0, 16).replace('.', '-');
                        // Parse the time stamp
                        Minute min = Minute.parseMinute(minuteTime);

                        // Ok, this is an ugly optimization. If the current time position in the file
                        // is more than a month (30 days) ahead of the start of the time window, we
                        // quick read two weeks worth of data, assuming that there is 4 samples per hour.
                        // This may lead to scanning past start of window if there are holes in the data
                        // series.
                        if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) {
                            for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) {
                                fileScanner.nextLine();
                            }
                            justOptimized = true;
                            continue;
                        }
                        // Detect if we have scanned past the window start position just after an optimization scan.
                        // If this is the case it may be because of the optimization. In that case we have to switch 
                        // optimization off and start over.
                        if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) {
                            logFile = new File(fileName);
                            fileScanner = new Scanner(logFile);
                            doOptimize = false;
                            continue;
                        }
                        justOptimized = false;
                        // Check if value is within time window
                        if ((min.getFirstMillisecond() > startTimeMs)
                                && (min.getFirstMillisecond() < stopTime.getTime())) {
                            // Parse the value
                            double value = Double.parseDouble((line.substring(20)).replace(',', '.'));
                            // Add the entry
                            timeSeries.add(min, value);
                            doOptimize = false;
                        }
                    }
                } catch (SeriesException se) {
                    // Bad entry, for example due to duplicates at daylight saving time switch
                } catch (NumberFormatException nfe) {
                    // Bad number format in a line, try to continue
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            fileScanner.close();
        }
    } catch (FileNotFoundException f) {
        System.out.println(f.toString());
    }

    // Create a collection for plotting
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(timeSeries);

    JFreeChart chart;

    int xSize = 750;
    int ySize = 450;
    // Customize colors and look of the Graph.
    if (look.equals("mobtemp")) {
        // Look for the mobile GUI
        chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false);
        XYPlot plot = chart.getXYPlot();
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        xSize = 175;
        ySize = 180;
    } else {
        // Create a Chart with time range as heading
        SimpleDateFormat localFormat = new SimpleDateFormat();
        String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime);
        chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false);

        Paint background = new Color(0x9D8140);
        chart.setBackgroundPaint(background);
        TextTitle title = chart.getTitle(); // fix title
        Font titleFont = title.getFont();
        titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0);
        title.setFont(titleFont);
        title.setPaint(Color.darkGray);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(background);
        plot.setDomainGridlinePaint(Color.darkGray);
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        plot.setRangeGridlinePaint(Color.darkGray);
        XYItemRenderer renderer = plot.getRenderer(0);
        renderer.setSeriesPaint(0, Color.darkGray);
        xSize = 750;
        ySize = 450;
    }

    try {
        res.setContentType("image/png");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "no-cache");
        res.setStatus(HttpServletResponse.SC_OK);
        ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

    p.flush();
    p.close();
    return;
}