为什么我的CSV文件无法将内容显示在图形上? [英] Why can't my CSV File display the content onto my graph?

查看:46
本文介绍了为什么我的CSV文件无法将内容显示在图形上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我的程序所做的是我有一个csv文件,该文件读取毫秒(我将其转换)和一个代表区域的字母.我试图将其显示为条形图,但每个字母(区域)都具有不同的选项卡.我的问题是试图将信件(从文件中)发送到我在选项卡中创建的特定区域.也许我缺少了一些东西,但我不确定.任何帮助都感激不尽.

Well basically what my program does is that I have a csv file that reads in the milliseconds (which I converted) and a letter that represents a zone. I am trying to display it as a bar chart but I have different tabs that each letter (zone) goes to. My issue is trying to send the letter (from file) to the specific zone which I made in tabs. Maybe I am missing something but I am not sure. Any help will be much appreciated.

这是我的代码:

@SuppressWarnings({ "serial", "deprecation" })
public class InductionTreeGraph extends JFrame {

static TimeSeries ts = new TimeSeries("data", Millisecond.class);

public static void add(JTabbedPane jtp, String label, int mnemonic, AbstractButton button1)
{
    int count = jtp.getTabCount();
    JButton button = new JButton(label);
    button.setBackground(Color.WHITE);
    jtp.addTab(label, null, button, null);
    jtp.setMnemonicAt(count, mnemonic);

}

public InductionTreeGraph() throws Exception {

        final XYDataset dataset = (XYDataset) createDataset();
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(1000, 400));
        setContentPane(chartPanel);

        JFrame frame = new JFrame("Induction Zone Chart");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTabbedPane jtp = new JTabbedPane();
        jtp.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        String zones[] = {"Zone A", "Zone B", "Zone C", "Zone S",
                "Zone SH","Zone W"};
        int mnemonic[] = {KeyEvent.VK_A, KeyEvent.VK_B, KeyEvent.VK_C,
                KeyEvent.VK_S, KeyEvent.VK_H,KeyEvent.VK_W};

        for (int i = 0, n=zones.length; i<n; i++)
        {
            AbstractButton button1 = null;
            InductionTreeGraph.add(jtp, zones[i], mnemonic[i], button1);
        }

        final JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        p.add(new JButton(new AbstractAction("Update") {

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

        }));

        frame.add(jtp, BorderLayout.NORTH);
        frame.add(p, BorderLayout.SOUTH);
        frame.getContentPane().add(chartPanel);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

}

    @SuppressWarnings("deprecation")
    private XYDataset createDataset() {
        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(ts);

        TreeMap<String,TreeMap<Integer,Integer[]>> zoneMap = getInductions("","");
        // 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 zone = zoneIT.next();
            TreeMap<Integer,Integer[]> hourCountsInZoneMap = zoneMap.get(zone);
            System.out.println("ZONE " + zone + " : ");
            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)");
                }
            }
        }

        return dataset;
}

    @SuppressWarnings("deprecation")
    private JFreeChart createChart(XYDataset dataset) {
        final JFreeChart chart = ChartFactory.createXYBarChart(
                "Induction Zone Chart", 
                "Hour", 
                true,
                "Inductions Per Minute", 
                (IntervalXYDataset) dataset, 
                PlotOrientation.VERTICAL,
                false, 
                true, 
                false
        );

        XYPlot plot = (XYPlot)chart.getPlot();
        XYBarRenderer renderer = (XYBarRenderer)plot.getRenderer();
        renderer.setBarPainter(new StandardXYBarPainter());
        renderer.setDrawBarOutline(false);
        ValueAxis axis = plot.getDomainAxis();
            axis.setAutoRange(true);
            axis.setFixedAutoRange(60000.0);

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

        return chart;
    }

private TreeMap<String, TreeMap<Integer, Integer[]>> getInductions(String mills, String zone) {

    // TreeMap of Inductions for Every Minute in Day Per Zone...
    // Key = Zone
    // Value = TreeMap of Inductions per Minute per Hour:
    //          Key = Hour
    //          Value = Array of 60 representing Induction Rate Per Minute
    //                  (each element is the induction rate for that minute)
    TreeMap<String, TreeMap<Integer, Integer[]>> zoneMap = new TreeMap<String, TreeMap<Integer, Integer[]>>();

    // Input file name...
    String fileName = "/home/a002384/ECLIPSE/IN070914.CSV";

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

                // The millisecond value is the number 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(zone1))
                    hourCountsInZoneMap = zoneMap.get(zone1);
                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(zone1))
                    zoneMap.put(zone1, hourCountsInZoneMap);

            }
        }
        finally
        {
            br.close();
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return zoneMap;
}

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
    try {
        InductionTreeGraph dem = new InductionTreeGraph();
        dem.pack();
        dem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        while(true) {
            double millisecond = 2;
            double num = millisecond;
            System.out.println(num);
            ts.addOrUpdate(new Millisecond(), num);
            try {
                Thread.sleep(20);
            } catch (InterruptedException ex) {
                System.out.println(ex);
            }
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

}

推荐答案

我的第一个建议是关于此行:

My very first suggestion is about this line:

setContentPane(chartPanel);

不要弄乱内容窗格.请改用以下行:

Don't mess with content pane. Use this line instead:

getContentPane().add(chartPanel);


我在您的代码中看到的问题是 InductionTreeGraph JFrame 扩展而来,您正在将此 chartPanel 设置为该框架的内容窗格,但是然后您使用一个新的 JFrame 局部变量(称为 frame ),并将此 chartPanel 也添加到此框架中:


The prooblem I see in your code is that InductionTreeGraph extends from JFrame and you are setting this chartPanel as this frame's content pane, but then you use a new JFrame local variable (called frame) and add this chartPanel to this frame as well:

JFrame frame = new JFrame("Induction Zone Chart");
...
frame.getContentPane().add(chartPanel);

Swing组件旨在按原样"使用,因此与继承相比,它是更可取的组成.话虽如此,您应该考虑在类声明中删除 extends JFrame 并将所有组件(图表面板,按钮等)添加到此本地 frame 中.

Swing components are intended to be used "as is" so it's preferable composition over inheritance. Having said this you should consider remove extends JFrame on your class declaration and add all your components (chart panel, buttons, etc) to this local frame instead.

您可能想看看此问题与解答中显示的示例.这或@trashgod在Stack Overflow中有关 JFreeChart 的所有示例(例如)可能会为您提供帮助更好地组织代码.

You may want to take a look to the example shown in this Q&A. This or any @trashgod's examples in Stack Overflow about JFreeChart (f.e. this one) might help you to better structure your code.

这篇关于为什么我的CSV文件无法将内容显示在图形上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆