点击按钮时,JFreeChart不会出现

时间:2016-05-03 23:54:08

标签: java swing jfreechart

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

这是UI类:

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

}

类从信号文件中读取数据,其中包含一些双数字,如下所示:

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;
    }
}

2 个答案:

答案 0 :(得分:2)

而不是替换动作处理程序中的图表,只需更新图表数据集中的相关系列。为了使下面的示例自成一体,我已替换readFile()并将返回类型更改为List<Double>

  

我不明白我犯了什么错误?

您尝试add()新的ChartPanel&#34;会使组件层次结构无效。如果已经显示了容器,则必须在此后验证层次结构以显示添加的组件。&#34;下面显示的方法消除了这种需要。

image

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 http://stackoverflow.com/a/37020264/230513
 */
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);
    }
}

答案 1 :(得分:0)

this.revalidate(); //is your solution.

单击按钮后更新框架。因此,在图表更新时显示图表。