eremeykin.pete.plotter.CartesianPlotterTopComponent.java Source code

Java tutorial

Introduction

Here is the source code for eremeykin.pete.plotter.CartesianPlotterTopComponent.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package eremeykin.pete.plotter;

import eremeykin.pete.api.core.centrallookupapi.CentralLookup;
import eremeykin.pete.api.core.logger.Logger;
import eremeykin.pete.api.core.logger.LoggerManager;
import eremeykin.pete.api.core.workspace.WorkspaceManager;
import eremeykin.pete.api.model.Model;
import eremeykin.pete.api.model.ModelChangedEvent;
import eremeykin.pete.api.model.ModelChangedListener;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javafx.application.Platform;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;

/**
 * Top component which displays something.
 */
//@ConvertAsProperties(
//        dtd = "-//eremeykin.pete.plotter//CartesianPlotter//EN",
//        autostore = false
//)
@TopComponent.Description(preferredID = "CartesianPlotterTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = false)
@ActionID(category = "Window", id = "eremeykin.pete.plotter.CartesianPlotterTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_CartesianPlotterAction", preferredID = "CartesianPlotterTopComponent")
@Messages({ "CTL_CartesianPlotterAction=CartesianPlotter",
        "CTL_CartesianPlotterTopComponent=CartesianPlotter Window",
        "HINT_CartesianPlotterTopComponent=This is a CartesianPlotter window" })
public final class CartesianPlotterTopComponent extends TopComponent
        implements LookupListener, ModelChangedListener, FileWatcher.Updateable {

    private static final Logger LOGGER = LoggerManager.getLogger(PlotterTopComponent.class);
    private File home;
    Model model;
    private Lookup.Result<Model> modelResult = null;

    private final FileWatcher watchThread = new FileWatcher(this);
    private ChartPanel chartPanel;
    private XYPlot plot;

    public CartesianPlotterTopComponent() {
        initComponents();
        setName(Bundle.CTL_CartesianPlotterTopComponent());
        setToolTipText(Bundle.HINT_CartesianPlotterTopComponent());
        final XYSeriesCollection dataset = new XYSeriesCollection();

        final XYSeries toleranceSeries = new XYSeries("Tolerance");
        final XYSeries dataSeries = new XYSeries("U");

        dataset.addSeries(dataSeries);
        dataset.addSeries(toleranceSeries);
        final JFreeChart chart = createChart(dataset);
        chartPanel = new ChartPanel(chart);
        setLayout(new java.awt.BorderLayout());
        add(chartPanel, BorderLayout.CENTER);
        validate();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0,
                400, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 300,
                Short.MAX_VALUE));
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        modelResult = CentralLookup.getDefault().lookupResult(Model.class);
        modelResult.addLookupListener(this);
        home = WorkspaceManager.INSTANCE.getWorkspace();
        try {
            watchThread.start();
        } catch (IllegalThreadStateException exc) {
        }
    }

    @Override
    public void componentClosed() {
        model.removeModelChangedListener(this);
        watchThread.stopWatch();
    }

    void writeProperties(java.util.Properties p) {
        p.setProperty("version", "1.0");
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    private void clear() {

        //        toleranceSeries.clear();
        //        dataSeries.clear();
    }

    @Override
    public void update() {
        // for first rpt file
        if (model == null) {
            clear();
            return;
        }
        File[] rptFiles = home.listFiles(filter());
        // catch if there is no such file
        if (rptFiles.length == 0) {
            clear();
            return;
        }
        File firstRPT = rptFiles[0];

        Scanner scanner;
        try {
            scanner = new Scanner(firstRPT);
            scanner.useDelimiter("\\s+|\n");
        } catch (FileNotFoundException ex) {
            clear();
            return;
        }
        List<Map.Entry<Double, Double>> tmpList = new ArrayList<>();
        for (int i = 0; scanner.hasNext(); i++) {
            String line = scanner.next();
            try {
                double x1 = Double.valueOf(line);
                line = scanner.next();
                double x2 = Double.valueOf(line);
                //                System.out.println("x1=" + x1 + "\nx2=" + x2);
                tmpList.add(new AbstractMap.SimpleEntry<>(x1, x2));
            } catch (NumberFormatException ex) {
                // only if it is the third or following line
                if (i > 1) {
                    LOGGER.error("Error while parsing double from file: " + firstRPT.getAbsolutePath());
                    JOptionPane.showMessageDialog(this, "Error while parsing result file.", "Parsing error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }

        }
        if (tmpList.isEmpty()) {
            clear();
            return;
        }
        fillData(tmpList);

    }

    protected void fillData(List<Map.Entry<Double, Double>> tmpList) {
        final XYSeriesCollection dataset = new XYSeriesCollection();
        final XYSeries toleranceSeries1 = new XYSeries("es");
        final XYSeries toleranceSeries2 = new XYSeries("ei");
        final XYSeries dataSeries = new XYSeries("U");
        final XYSeries diameter = new XYSeries("d");

        for (Map.Entry<Double, Double> point : tmpList) {
            Double xv = point.getKey();
            Double yv = point.getValue();
            if (xv == null || yv == null) {
                continue;
            }
            dataSeries.add(xv, yv);
            toleranceSeries1.add(xv, Double.valueOf(model.getParameterByID(model.getRoot(), 5).getValue()));
            toleranceSeries2.add(xv, Double.valueOf("-" + model.getParameterByID(model.getRoot(), 5).getValue()));
            diameter.add(xv, Double.valueOf(0));
        }
        dataset.addSeries(dataSeries);
        dataset.addSeries(toleranceSeries1);
        dataset.addSeries(toleranceSeries2);
        dataset.addSeries(diameter);
        plot.setDataset(dataset);
    }

    JFreeChart createChart(XYDataset dataset) {
        // create the chart...
        final JFreeChart chart = ChartFactory.createXYLineChart(" ?", // chart title
                "???", // x axis label
                "", // y axis label
                dataset, // data
                PlotOrientation.VERTICAL, true, // include legend
                true, // tooltips
                false // urls
        );

        chart.setTitle(new org.jfree.chart.title.TextTitle(" ?",
                new java.awt.Font("Arial", java.awt.Font.PLAIN, 16)));

        chart.setBackgroundPaint(Color.white);
        plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.WHITE);
        //    plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
        plot.setDomainGridlinePaint(Color.DARK_GRAY);
        plot.setRangeGridlinePaint(Color.DARK_GRAY);
        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesShapesVisible(0, true);
        renderer.setSeriesShapesVisible(1, false);
        renderer.setSeriesShapesVisible(2, false);
        renderer.setSeriesShapesVisible(3, false);
        renderer.setSeriesPaint(0, Color.RED);
        renderer.setSeriesPaint(1, Color.BLUE);
        renderer.setSeriesPaint(2, Color.BLUE);
        renderer.setSeriesPaint(3, Color.BLACK);
        //        renderer.setSeriesStroke(1, new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {6.0f, 6.0f}, 0.0f ));
        plot.setRenderer(renderer);
        return chart;
    }

    FilenameFilter filter() {
        return new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith("Z.rpt");
            }
        };
    }

    @Override
    public void modelChanged(ModelChangedEvent evt) {
        update();
    }

    @Override
    public void resultChanged(LookupEvent ev) {
        Collection<? extends Model> allModels = modelResult.allInstances();
        if (!allModels.isEmpty()) {
            model = allModels.iterator().next();
            modelChanged(null);
        }
    }

    @Override
    public File home() {
        return home;
    }
}