Adding dynamic line chart to JPanel in existing JFrame using JFreeChart <java>

旧街凉风 提交于 2021-02-08 11:01:07

问题


I made an application that would show me Max, Minimum, and Average ping when I click "start" in my JFrame application. I made a white box so I could fit a dynamically changing line graph that will be in the same window as my stats, and will update at the same rate as my stats (1 second).

No matter how much I google, everybody seems to understand the JFreeChart sample code. I do not understand how to implement that at all. Other tutorials show just the graph as a standalone in its own window.

I hope somebody can help me. Here is my code for the JFrame as of now:

 private void startButtonMouseClicked(java.awt.event.MouseEvent evt) {                                         
   String host = hostName.getText();


    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable(){
        @Override
        public void run(){

            try { 
                NetworkAnalyzer.pingCheck(host);

            } catch (IOException ex) {
                Logger.getLogger(NetworkAnalyzerwindow.class.getName()).log(Level.SEVERE, null, ex);

            }
        }
    }, 0, 1, TimeUnit.SECONDS);

And here is my pingCheck:

public class NetworkAnalyzer {
static int count=0;
static long max_time = 0;
static long min_time = 0;
static long avg_time = 0;

public static void pingCheck(String host) throws IOException{
String time = "";
//command to execute
 String pingCmd = "ping " + host + " -t " + "-n 1"; 

 //gets runtime to execute command
 Runtime runtime = Runtime.getRuntime(); 
 try {
     Process process = runtime.exec(pingCmd);

     //gets inputstream to read the output of the cocmmand
     BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

     //read outputs
     String inputLine = in.readLine();
     while((inputLine != null)) {
         if (inputLine.length() > 0 && inputLine.contains("time")){
             time = inputLine.substring(inputLine.indexOf("time"));
             break;
         }
         inputLine = in.readLine();
     } 
    /* if(inputLine.contains("timed")){
         System.out.print("Request timed out. Try another domain:");

         pingCheck(time);
     }*/ 

         time = time.replaceAll("[^0-9]+", " ");
         time = time.substring(0, Math.min(time.length(), 3));
         time = time.replaceAll(" ", "");
         System.out.println("ping:" + time);
         //ping calcs


         count++;
         Long ping;
         ping = Long.parseLong(time);
         //for avg                  
         //max ping


         if( count == 1 || ping >= max_time)
             max_time = ping;

         //min ping
         if(count == 1 || ping <= min_time)
             min_time = ping;
         //avg ping


         if (count > 0)
             avg_time = (avg_time*(count-1)+ping)/count;


         NetworkAnalyzerwindow.maxPing.setText("Max: " + max_time + "ms");
         NetworkAnalyzerwindow.minPing.setText("Min: " + min_time + "ms");
         NetworkAnalyzerwindow.avgPing.setText("Avg: " + avg_time + "ms"); 

 } catch(IOException | NumberFormatException ex){
     JOptionPane.showMessageDialog(null, ex);
 }


}

I just want to add a dynamically changing graph that would take the ping values and graph them. Can somebody actually help me and not link me to one of the tutorials that only shows how to make a graph by itself.

Here is what the app looks like when running(I would like the graph in the white box. I could make the box bigger):

http://imgur.com/kgYCoW2


回答1:


Using ProcessBuilder, shown here, execute the ping command in your doInBackground() implementation of a SwingWorker. Parse the output, and publish() the results. Update the dataset in your process() implementation, and the chart will update itself in response. An example using JFreeChart is shown here.

Can you explain a bit more?

Starting with the first example, replace

ProcessBuilder pb = new ProcessBuilder("ls", "-lR", "/");

with

ProcessBuilder pb = new ProcessBuilder("ping", "-c", "3", "example.com");

to get a convenient display of the standard output of ping. In outline, your process() in the second example might look like this:

@Override
protected void process(java.util.List<String> messages) {
    for (String message : messages) {
        textArea.append(message + "\n");
        // parse x, y from message 
        series.add(x, y);
    }
}


来源:https://stackoverflow.com/questions/32239281/adding-dynamic-line-chart-to-jpanel-in-existing-jframe-using-jfreechart-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!