简体   繁体   English

Java Swing图不显示

[英]Java Swing graph doesn't display

I'm trying to read a CSV file and plot a graph based on it. 我正在尝试读取CSV文件并基于该文件绘制图形。 However, when the frame shows up, it is empty. 但是,当框架出现时,它是空的。 Any idea where I am going wrong? 知道我要去哪里错吗?

import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Color;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;


public class Poly extends JPanel
{
 int time[]=new int[10000];
 int generated[]=new int[10000];

public void paintComponent( Graphics g )
{
    super.paintComponent( g ); 
    // Draw a Polygone
    //int xValues[] = { 20, 40, 50, 30, 20, 15 };
    //int yValues[] = { 50, 50, 60, 80, 80, 60 };
    //Polygon polygon1 = new Polygon( xValues, yValues, 6 );
    //g.drawPolygon( polygon1 );                            
    // Draw a Polyline
    //int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };
    //int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };
    g.setColor(Color.RED);
    g.drawPolyline( time, generated, 10000 );              
}

public void run()
{
    String csvFile = "VaryHarvesterSize_VaryEnergyBufferMax_InputFile(64050KPIT2011_AllYear.dat.keep).csv";
    String line = "";
    String cvsSplitBy = ",";
    int k=0;

    try
    {
        File summaryFile=new File(csvFile);
        Scanner reader = new Scanner(summaryFile);
        reader.nextLine();

        //System.out.println(reader.nextLine());
        while(k<10000)
        {
            // use comma as separator
            line = reader.nextLine();
            String[] record = line.split(cvsSplitBy);
            double temp=Double.parseDouble(record[0].trim());
    time[k]=(int)temp;
            temp = Double.parseDouble(record[3].trim());
    generated[k]=(int)temp;
            //System.out.println(record);
            //System.out.println("Time="+time[k]+" Energy="+generated[k]);
            k++;

        }
    }

    catch(Exception e)
    {

        e.printStackTrace();
    }



}


public static void main (String[] args)
{
    Poly obj=new Poly();
    obj.run();


    JFrame frame=new JFrame("Polygone And Polyline")   ;
    JPanel policePanel=new Poly();
    frame.add(policePanel);
    frame.setSize(400,400);
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}

I tried with hard coded values, it shows up on the frame. 我尝试使用硬编码的值,它显示在框架上。 But the values in the file don't. 但是文件中的值没有。

JPanel policePanel=new Poly();
    frame.add(policePanel);

Here you are adding a new panel to the frame. 在这里,您要向框架添加一个新面板。 However you have called run on another instance of Poly before this. 但是,在此之前,您已调用Run在Poly的另一个实例上。 That means the data is being populated in another instance which you haven't added to the frame. 这意味着数据正在另一个尚未添加到框架的实例中填充。 Instead call 'run' on this instance and it should work. 而是在此实例上调用“运行”,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM