当我单击按钮时,没有显示JFreeChart [英] JFreeChart doesn't appear when I click on button

查看:84
本文介绍了当我单击按钮时,没有显示JFreeChart的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在面板中没有看到此代码的输出,但是在控制台点(X,Y)上出现了. 我搜索的越来越多,一无所获.

I see no output for this code in panel, but in console points (X,Y) come out. I searched more and more and nothing.

这是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                   

}

Class从信号文件中读取数据,其中包括一些双精度数字,如下所示:

Class reads data from signal file which include some double numbers like this:

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

推荐答案

代替替换您动作处理程序中的图表,只需 update 图表数据集中的相关序列.为了使下面的示例完整,我替换了readFile()并将返回类型更改为List<Double>.

Instead of replacing the chart in your action handler, simply update the relevant series in the chart's dataset. To make the example below self-contained, I've substituted readFile() and changed the return type to List<Double>.

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

I don't understand what error I make?

您尝试 add() 一个新的ChartPanel使组件层次结构无效.如果已经显示了容器,则此后必须验证该层次结构才能显示添加的组件.下面显示的方法消除了这种需求.

Your attempt to add() a new 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." The approach shown below obviates the need.

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

这篇关于当我单击按钮时,没有显示JFreeChart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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