0

My program is up and working like I wanted it but now I want to implement Runnable in my program so I could show each tab that my chart runs. How should I do this? I've tried using the methods that I did before but I could not correlate it into my program.

    public class Induction {

      final static String titles[] = {"A","B","C","S", "SH", "W"};
      private final static TimeSeriesCollection all = new TimeSeriesCollection();
      static Day day = new Day(9,7,2014);

      private static TimeSeriesCollection createInduction() {

        for (String s : titles) {
            all.addSeries(new TimeSeries(s));
        }

        // while parsing the CSV file
        String zone = "/home/a002384/ECLIPSE/IN070914.CSV";
        TimeSeries ts = all.getSeries(zone);

        TreeMap<String, TreeMap<Integer, Integer[]>> zoneMap = new TreeMap<String, TreeMap<Integer, Integer[]>>();
        try{
            BufferedReader bufferedReader = new BufferedReader(new FileReader(zone));
            String line;
            try {
                // Read a line from the csv file until it reaches to the end of the file...
                while ((line = bufferedReader.readLine()) != null)
                {
                    // Parse a line of text in the CSV
                    String [] indData = line.split("\\,");
                    long millisecond = Long.parseLong(indData[0]);
                    String zones = indData[1];

                    // The millisecond value is the # of milliseconds since midnight
                    // From this, we can derive the hour and minute of the day
                    // as follows:
                    int secOfDay = (int) (millisecond / 1000);
                    int hrOfDay = secOfDay / 3600;
                    int minInHr = secOfDay % 3600 / 60;

                    // Obtain the induction rate TreeMap for the current zone
                    // If this is a "newly-encountered" zone, create a new TreeMap
                    TreeMap<Integer, Integer[]> hourCountsInZoneMap;
                    if (zoneMap.containsKey(zones))
                        hourCountsInZoneMap = zoneMap.get(zones);
                    else
                        hourCountsInZoneMap = new TreeMap<Integer, Integer[]>();

                    // Obtain the induction rate array for the current hour
                    // in the current zone.
                    // If this is a new hour in the current zone, create a
                    // new array, and initialize this array with all zeroes.
                    // The array is size 60, because there are 60 minutes in
                    // the hour. Each element in the array represents the
                    // induction rate for that minute
                    Integer [] indRatePerMinArray;
                    if (hourCountsInZoneMap.containsKey(hrOfDay))
                        indRatePerMinArray = hourCountsInZoneMap.get(hrOfDay);
                    else
                    {
                        indRatePerMinArray = new Integer[60];
                        Arrays.fill(indRatePerMinArray, 0);
                    }

                    // Increment the induction rate for the current minute
                    // by one. Each line in the csv file represents a
                    // single induction at a single point in time
                    indRatePerMinArray[minInHr]++;

                    // Add everything back into the TreeMaps if these are
                    // newly created.
                    if (!hourCountsInZoneMap.containsKey(hrOfDay))
                        hourCountsInZoneMap.put(hrOfDay, indRatePerMinArray);

                    if (!zoneMap.containsKey(zones))
                        zoneMap.put(zones, hourCountsInZoneMap);
                }
            }
            finally
            {
                bufferedReader.close();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

        // Iterate through all zones and print induction rates
        // for every minute into every hour by zone ...
        Iterator<String> zoneIT = zoneMap.keySet().iterator();
        while (zoneIT.hasNext())
        {
            String zones2 = zoneIT.next();
            TreeMap<Integer, Integer[]> hourCountsInZoneMap = zoneMap.get(zones2);
            System.out.println("ZONE " + zones2 + ":");
            Iterator<Integer> hrIT = hourCountsInZoneMap.keySet().iterator();
            while (hrIT.hasNext())
            {
                int hour = hrIT.next();
                Integer [] indRatePerMinArray = hourCountsInZoneMap.get(hour);
                for (int i = 0; i < indRatePerMinArray.length; i++)
                {
                    System.out.print(hour + ":");
                    System.out.print(i < 10 ? "0" + i : i);
                    System.out.println(" = " + indRatePerMinArray[i] + "induction(s)");
                }
            }
        }

        TimeSeries s1 = new TimeSeries("A");
        TreeMap<Integer, Integer[]> dayAZone = zoneMap.get("A");
        Iterator<Integer> hourIT = dayAZone.keySet().iterator();
        while (hourIT.hasNext())
        {
            Integer indHour = hourIT.next();
            Hour hour = new Hour(indHour, day);
            Integer [] indMins = dayAZone.get(indHour);
            for (int i = 0; i < 60; i++)
                s1.addOrUpdate(new Minute(i, hour), indMins[i]);
                System.out.println(zoneMap);
        }

        TimeSeries s2 = new TimeSeries("B");
        TreeMap<Integer, Integer[]> dayBZone = zoneMap.get("B");
        Iterator<Integer> hourIT1 = dayBZone.keySet().iterator();
        while (hourIT1.hasNext())
        {
            Integer indHour = hourIT1.next();
            Hour hour = new Hour(indHour, day);
            Integer [] indMins = dayBZone.get(indHour);
            for (int i = 0; i < 60; i++)
                s2.addOrUpdate(new Minute(i, hour), indMins[i]);
                System.out.println(zoneMap);
        }

        TimeSeries s3 = new TimeSeries("C");
        TreeMap<Integer, Integer[]> dayCZone = zoneMap.get("C");
        Iterator<Integer> hourIT2 = dayCZone.keySet().iterator();
        while (hourIT2.hasNext())
        {
            Integer indHour = hourIT2.next();
            Hour hour = new Hour(indHour, day);
            Integer [] indMins = dayCZone.get(indHour);
            for (int i = 0; i < 60; i++)
                s3.addOrUpdate(new Minute(i, hour), indMins[i]);
                System.out.println(zoneMap);
        }

        TimeSeries s4 = new TimeSeries("S");
        TreeMap<Integer, Integer[]> daySZone = zoneMap.get("S");
        Iterator<Integer> hourIT3 = daySZone.keySet().iterator();
        while (hourIT3.hasNext())
        {
            Integer indHour = hourIT3.next();
            Hour hour = new Hour(indHour, day);
            Integer [] indMins = daySZone.get(indHour);
            for (int i = 0; i < 60; i++)
                s4.addOrUpdate(new Minute(i, hour), indMins[i]);
                System.out.println(zoneMap);
        }

        TimeSeries s5 = new TimeSeries("SH");
        TreeMap<Integer, Integer[]> daySHZone = zoneMap.get("SH");
        Iterator<Integer> hourIT4 = daySHZone.keySet().iterator();
        while (hourIT4.hasNext())
        {
            Integer indHour = hourIT4.next();
            Hour hour = new Hour(indHour, day);
            Integer [] indMins = daySHZone.get(indHour);
            for (int i = 0; i < 60; i++)
                s5.addOrUpdate(new Minute(i, hour), indMins[i]);
                System.out.println(zoneMap);
        }

        TimeSeries s6 = new TimeSeries("W");
        TreeMap<Integer, Integer[]> dayWZone = zoneMap.get("W");
        Iterator<Integer> hourIT5 = dayWZone.keySet().iterator();
        while (hourIT5.hasNext())
        {
            Integer indHour = hourIT5.next();
            Hour hour = new Hour(indHour, day);
            Integer [] indMins = dayWZone.get(indHour);
            for (int i = 0; i < 60; i++)
                s6.addOrUpdate(new Minute(i, hour), indMins[i]);
                System.out.println(zoneMap);
        }

        all.addSeries(s1);
        all.addSeries(s2);
        all.addSeries(s3);
        all.addSeries(s4);
        all.addSeries(s5);
        all.addSeries(s6);

        return all;

    }

    private static ChartPanel createPane(String title) {

        TimeSeriesCollection dataset = new ``TimeSeriesCollection(all.getSeries(title));
        int j = 0;
        JFreeChart chart = ChartFactory.createXYBarChart(
                "Induction Chart Zone ", 
                "Hour", 
                true, 
                "Inductions Per Minute", 
                dataset, 
                PlotOrientation.VERTICAL, 
                false, 
                true, 
                false
                );

        XYPlot plot = (XYPlot)chart.getPlot();
        XYBarRenderer renderer = (XYBarRenderer)plot.getRenderer();
        renderer.setBarPainter(new StandardXYBarPainter());
        renderer.setDrawBarOutline(false);

        // Set an induction of 30 per minute...
        Marker target = new ValueMarker(30);
        target.setPaint(java.awt.Color.blue);
        target.setLabel("Rate");
        plot.addRangeMarker(target);

        return new ChartPanel(chart);

    }

public static void main(String[] args) {
    createInduction();
    final JFrame frame = new JFrame("Induction Zone Chart");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JTabbedPane jtp = new JTabbedPane();

    final int j = 0;
    jtp.add(titles[j], createPane("A"));
    jtp.add(titles[j+1], createPane("B"));
    jtp.add(titles[j+2], createPane("C"));
    jtp.add(titles[j+3], createPane("S"));
    jtp.add(titles[j+4], createPane("SH"));
    jtp.add(titles[j+5], createPane("W"));
    for (String s : titles) {
        jtp.add(createPane(s));
    }
    jtp.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

    ChartPanel chart = null;

    for (int i = 0; i < titles.length; i++) 
    {
        chart = createPane(titles[i].substring(1, titles[i].length()));
    }

    final JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    p.add(new JButton(new AbstractAction("Update") {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent e) {
            frame.repaint();
        }
    }));


    ChangeListener changeListener = new ChangeListener() {
        public void stateChanged(ChangeEvent changeEvent) {
            JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
            int index = sourceTabbedPane.getSelectedIndex();
            String tabTitle = sourceTabbedPane.getTitleAt(index);
            createPane(tabTitle.substring(0, tabTitle.length()));
            System.out.println("Source to " + tabTitle);
        }
    };

    while (jtp.getTabCount() > 6)
        jtp.remove(6);

    jtp.addChangeListener(changeListener);
    frame.add(jtp, BorderLayout.CENTER);
    frame.add(p, BorderLayout.SOUTH);

    frame.setPreferredSize(new Dimension(1000, 600));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

}

c.torres
  • 31
  • 1
  • 6

1 Answers1

2

Update each chart's model, an instance of TimeSeries, in the background of a SwingWorker. A complete example is shown here. The listening view, an instance of ChartPanel, will update itself accordingly.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Can you give me an outline of how I can go about using Swingworker? @trashgod – c.torres Aug 01 '14 at 16:37
  • I cited the [one that update a chart's model](http://stackoverflow.com/a/13205322/230513); more related examples [here](http://stackoverflow.com/search?tab=votes&q=user%3a230513%20%5bSwingWorker%5d). – trashgod Aug 01 '14 at 16:44
  • I want to be able to make my bar chart to go up and down while the chart is moving, can Swingworker do that or should I try implementing Runnable method? @trashgod – c.torres Aug 01 '14 at 18:10
  • Simply animating a chart may be easier with `javax.swing.Timer`, seen [here](http://stackoverflow.com/a/5048863/230513); compare this with the example cited in your previous [question](http://stackoverflow.com/q/24961466/230513). – trashgod Aug 01 '14 at 20:37
  • I looked at my code and the code you referenced and I am not sure what to put in my Timer code for my graphs to go up and down. You think you have an outline of how to use Timer in my program? @trashgod – c.torres Aug 04 '14 at 16:34
  • I'm not sure what to add; either way, you'd invoke `readLine()` in the worker's background or the timer's action handler. – trashgod Aug 04 '14 at 16:48
  • Do you think it is easier to display each of the charts going up and down in a Timer for each graph or in a Swingworker? Using the data from a csv file? @trashgod – c.torres Aug 07 '14 at 22:46
  • `Timer` is sufficient, but go with `SwingWorker` if the GUI must remain responsive while loading. – trashgod Aug 07 '14 at 23:57
  • Should I make different Swingworkers or can I put it into one Swingworker? @trashgod – c.torres Aug 08 '14 at 18:15
  • You're reading one file, so one worker should be enough; your implementation of `process()` can decide which `TimeSeries` to update. – trashgod Aug 08 '14 at 20:12