Menu

how to add JChart2D on Jpanel in netbeans

Help
Mahesh
2012-11-02
2013-04-06
  • Mahesh

    Mahesh - 2012-11-02

    I am struggling for adding Jchart2D on Jpanel on netbeans. Please check following code for:-

    package graph;

    import info.monitorenter.gui.chart.Chart2D;
    import info.monitorenter.gui.chart.ITrace2D;
    import info.monitorenter.gui.chart.traces.Trace2DLtd;

    import java.awt.Color;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.Timer;
    import java.util.TimerTask;

    import javax.swing.JFrame;

    public class gr extends javax.swing.JFrame
    {
    Chart2D chart = new Chart2D();
    final ITrace2D trace = new Trace2DLtd(200);

    public gr()
    {
    initComponents();
    chart.addTrace(trace);
    trace.setColor(Color.RED);
    grpanel.add(chart);
    grpanel.setVisible(true);
    Timer timer = new Timer(true);
    TimerTask task = new TimerTask()
    {
    private double m_y = 0;
    private long m_starttime = System.currentTimeMillis();
    public void run()
    {
    double rand = Math.random();
    boolean add = (rand >= 0.5) ? true : false;
    this.m_y = (add) ? this.m_y + Math.random() : this.m_y - Math.random();
    trace.addPoint(((double) System.currentTimeMillis() - this.m_starttime), this.m_y);
    }
    };

    timer.schedule(task, 1000, 20);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    grpanel = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout grpanelLayout = new javax.swing.GroupLayout(grpanel);
    grpanel.setLayout(grpanelLayout);
    grpanelLayout.setHorizontalGroup(
    grpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 547, Short.MAX_VALUE)
    );
    grpanelLayout.setVerticalGroup(
    grpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 502, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(67, 67, 67)
    .addComponent(grpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(585, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(44, 44, 44)
    .addComponent(grpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(251, Short.MAX_VALUE))
    );

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

    /**
    * @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(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    JFrame frame = new JFrame("MinimalDynamicChart");
    frame.setVisible(true);
    frame.setSize(400,300);
    }
    // Variables declaration - do not modify
    private javax.swing.JPanel grpanel;
    // End of variables declaration
    }

    But when i try to add chart on JFrame then it works without error….
    so please suggest me how to add it is on JPanel.

     
  • Achim Westermann

    Hi,
    1. mistake: You never insantiate gr, the whole code does not get executed.

    -  JFrame frame = new JFrame();
    +  JFrame frame = new gr();

    2. I hacked away all layout-manager stuff and used a simple BorderLayout. That seems to stretch the chart to full size:

    import info.monitorenter.gui.chart.Chart2D;
    import info.monitorenter.gui.chart.ITrace2D;
    import info.monitorenter.gui.chart.traces.Trace2DLtd;

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.util.Timer;
    import java.util.TimerTask;

    import javax.swing.JFrame;

    public class gr extends javax.swing.JFrame {
      Chart2D chart = new Chart2D();

      final ITrace2D trace = new Trace2DLtd(200);

      public gr() {
        initComponents();
        grpanel = new javax.swing.JPanel();
        grpanel.setLayout(new BorderLayout());
        chart.addTrace(trace);
        trace.setColor(Color.RED);
        grpanel.add(chart,BorderLayout.CENTER);
        getContentPane().add(grpanel, BorderLayout.CENTER);

    //    grpanel.setVisible(true);
        Timer timer = new Timer(true);
        TimerTask task = new TimerTask() {
          private double m_y = 0;

          private long m_starttime = System.currentTimeMillis();

          public void run() {
            double rand = Math.random();
    //        System.out.println("timer");
            boolean add = (rand >= 0.5) ? true : false;
            this.m_y = (add) ? this.m_y + Math.random() : this.m_y - Math.random();
            trace.addPoint(((double) System.currentTimeMillis() - this.m_starttime), this.m_y);
          }
        };

        timer.schedule(task, 1000, 20);
      }

      @SuppressWarnings("unchecked")
      // <editor-fold defaultstate="collapsed" desc="Generated Code">
      private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

      }// </editor-fold>

      /**
       * @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(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
          java.util.logging.Logger.getLogger(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
          java.util.logging.Logger.getLogger(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
          java.util.logging.Logger.getLogger(gr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        // </editor-fold>
        JFrame frame = new gr();
        frame.setSize(400, 300);
        frame.setVisible(true);
      }

      // Variables declaration - do not modify
      private javax.swing.JPanel grpanel;
      // End of variables declaration
    }

    HTH,
    Achim

     
  • Mahesh

    Mahesh - 2012-11-07

    Hi … expert ,

    I have changed my code as per your suggestions and there is no any compile error while execution of these code but Graph does not display on Jpanel.  

     
  • Achim Westermann

    Hi waghmalemahesh,

    feel free to call me Achim. Just paste your code here and I'll have a look.

    cheers,
    Achim

     
  • Mahesh

    Mahesh - 2012-11-08

    Hi….. Achim

    Thanks for your suggestions and friendly communication….. I have changed my decision and i drawn graph on JFrame and as per your example code it works better. Any case…. if i will change my decision for drawing graph on JPanel than please help me in future.
    ------- In my application currently i have used ITrace2D and it work better but there is no parallel lines to XY coordinate for each value…. My another question is that is there any method in JChart2D to draw lines parallel to XY coordinate for each value on XY coordinate ?

    Thanks and Regards Mr. Achim

     
  • Achim Westermann

    Hi waghmlemahesh,

    I'm not completely sure what you want to achieve. I guess you want to have a line through the chart for every scale tick.
    This could be achived by:

        chart.getAxisX().setPaintGrid(true);
        chart.getAxisY().setPaintGrid(true);

    HTH,
    Achim

     
  • Achim Westermann

    Also for the JPanel - Case:
    In case you decide to use a different LayoutManager on it you could consider to read the javadoc of that LayoutManager and use the methods:
    - setPrefferedSize(..)
    - setMinimumSize(..)
    - setMaximumSize(..)
    on the chart instance.
    Different LayoutManagers work differently with those dimensions.

    cheers,
    Achim

     
  • Mahesh

    Mahesh - 2012-11-09

    Hi Achim..
                            Your code,
                                                  chart.getAxisX().setPaintGrid(true);
                                                  chart.getAxisY().setPaintGrid(true);

    for drawing Lines parallel to XY coordinate for each value is really helpful for my application.
    Thanks you so much….!!!!!

     
  • Arci

    Arci - 2012-11-09

    I'm sorry, also I wolud like to see a chart into a panel on a form.
    I create an application with Netbeas and put e simple code to see a random chart into a panel….., I have more problem. there was never error, but i can't see anything into the jpanel.

    my simple code:

    I create a function :

    public Chart2D disegnaGraficoChart2D () {
            // Create a chart: 
            Chart2D chart = new Chart2D();
            // Create an ITrace:
            ITrace2D trace = new Trace2DSimple();
            // Add the trace to the chart. This has to be done before adding points (deadlock prevention):
            chart.addTrace(trace);
           
            Random random = new Random();
            for(int i=100;i>=0;i-){
                trace.addPoint(random.nextDouble()*3+i,random.nextDouble()*10.0+i);
            }
           
            return chart;
           
        }  

            And into a jbutton click

    private void BtnAvvioActionPerformed(java.awt.event.ActionEvent evt) { 
           
            jPanel2.add(disegnaGraficoChart2D(););
    }

    … I can't see anything.

    Can you help me?

     
  • Mahesh

    Mahesh - 2012-11-11

    Hi arcellacs
                           Before some day i had also face such problem of adding random chart on jpanel in netbeans… but i can't . So i used different method for that, which is:= 1) First add Jframe on Jpanel.
                                                                                       2) After that use method  frame_object.setUndecorated(true)  to hide the    
                                                                                            titlebar  of Jframe. And after add your random chart on that frame.
                           I know these is not perfect solution for your question, but it look like what u want exact and it work better in my application. I am also trying to see a random chart into jpanel if i found solution then immediately i will contact with you.

    Cheers ,
    Mahesh                                                                          

     
  • Arci

    Arci - 2012-11-12

    thank's, I try this solution!

     

Anonymous
Anonymous

Add attachments
Cancel





Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.