当我点击按钮时 JFreeChart 没有出现

JFreeChart doesn't appear when I click on button

我在面板中没有看到此代码的输出,但在控制台中点 (X,Y) 出来了。 我搜索了越来越多,什么也没有。

这是UI class:

/*
 * 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 com.dspTasks.UI;
import dsp.ReadFile;
import java.awt.BorderLayout;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import org.jfree.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
 *
 * @author fathy
 */
public class out extends javax.swing.JFrame {

/**
 * Creates new form out
 */

public out() {
    initComponents();
    this.setVisible(true);

}

/**
 * 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.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    loadSignal1 = new javax.swing.JButton();
    run = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    jLabel1.setText("path");

    jTextField1.setToolTipText("file path");
    jTextField1.setName("path"); // NOI18N

    loadSignal1.setText("load signal1");

    run.setText("run");
    run.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            runActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(391, 391, 391)
                    .addComponent(run))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(213, 213, 213)
                    .addComponent(loadSignal1))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(23, 23, 23)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(392, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(loadSignal1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 360, Short.MAX_VALUE)
            .addComponent(run))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

private void runActionPerformed(java.awt.event.ActionEvent evt) {                                    
    try {
        JPanel chartPanel=createChartPanel();
        this.add(chartPanel,BorderLayout.CENTER);
    } catch (FileNotFoundException ex) {
        System.err.println(ex);
    }

}                                   

private JPanel createChartPanel() throws FileNotFoundException{
    String chartTitle="signal chart";
    String XLabel="Voltage(V)";
    String YLabel = "Time(T)";
    XYDataset dataset=createDataSet();
    JFreeChart chart= ChartFactory.createXYLineChart(YLabel, YLabel, YLabel, dataset);
    return new ChartPanel(chart);
}
private XYDataset createDataSet() throws FileNotFoundException{
    XYSeriesCollection dataset=new XYSeriesCollection();
    XYSeries signal1=new XYSeries("signal1");
    //XYSeries signal2= new XYSeries("signal2");
    ArrayList dataSignal=ReadFile.readFile();
    for(int i=0;i<dataSignal.size();i++){
        signal1.add(i+1, (Double) dataSignal.get(i));
    }
    dataset.addSeries(signal1);
    for(int i=0;i<2000;i++){
        System.out.println(signal1.getDataItem(i));
    }

    return dataset;
}
/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(out.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(out.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(out.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(out.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new out().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton loadSignal1;
private javax.swing.JButton run;
// End of variables declaration                   

}

Class 从信号文件中读取数据,其中包含一些像这样的双数:

4
3.99950652992664
3.99802624146293
3.99555949984788
3.99210691371309
3.98766933493251
3.98224785841232
3.97584382182072
3.96845880525791
3.96009463086623
3.95075336238055
3.94043730461910
3.92914900291476
3.91689124248706
3.90366704775499
3.88947968159071
3.87433264451452
3.85822967383119
3.84117474270777
3.82317205919332
3.80422606518061

读取文件:

package dsp;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

/*
 * 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.
 */

/**
 *
 * @author fathy
 */
public class ReadFile {


    public static ArrayList readFile() throws FileNotFoundException{
        ArrayList signalData= new ArrayList();

        Scanner input = new Scanner(new File("signal1"));
        while(input.hasNext()){
            signalData.add(input.nextDouble());
        }
        return signalData;
    }
}
this.revalidate(); //is your solution.

它会在您单击按钮后更新框架。因此,使图表显示为框架更新。

无需替换 操作处理程序中的图表,只需更新 图表数据集中的相关系列。为了使下面的示例独立,我替换了 readFile() 并将 return 类型更改为 List<Double>.

I don't understand what error I make?

您尝试 add() 一个新的 ChartPanel "invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component." 下面显示的方法消除了需要。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * @see 
 */
public class Test {

    private final XYSeries signal = new XYSeries("signal");
    private final XYSeriesCollection dataset = new XYSeriesCollection(signal);

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFreeChart chart = ChartFactory.createXYLineChart(
            "Signal chart", "Time(T)", "Voltage(V)", dataset);
        f.add(new ChartPanel(chart));
        JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        p.add(new JButton(new AbstractAction("Load signal") {
            @Override
            public void actionPerformed(ActionEvent e) {
                signal.clear();
                List<Double> list = ReadFile.readFile();
                int i = 0;
                for (Double d : list) {
                    signal.add(i++, d);
                }
            }
        }));
        f.add(p, BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static class ReadFile {

        private static final Random R = new Random();

        public static List<Double> readFile() {
            List<Double> list = Stream.iterate(4.0, x -> x - (R.nextDouble() / 42))
                .limit(42).collect(Collectors.toList());
            return list;
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test()::display);
    }
}