Drawing Graphs

Hi,
Anybody tell me how to draw the Graphs in JFrame. I want to have months 1,...12 on X-axis and Values for each month on Y-axis.
|
v |
a |
l | .
u | . .
e |________.________________
1 2 3 4 ... 12 month-->
I do not have any idea how to make 2D graphics in java. Help me with an example so that i can understand very easily and do my work very fast.
Thanks,

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class LineGraph
    public static void main(String[] args)
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new GraphPanel());
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class GraphPanel extends JPanel
    final int
        HPAD = 60,
        VPAD = 40;
    int[] data;
    Font font;
    public GraphPanel()
        data = new int[] {
            120, 190, 211, 75, 30, 290, 182, 65, 85, 120, 100, 101
        font = new Font("lucida sans regular", Font.PLAIN, 16);
        setBackground(Color.white);
    protected void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        int w = getWidth();
        int h = getHeight();
        // scales
        float xInc = (w - HPAD - VPAD) / 11f;
        float yInc = (h - 2*VPAD) / 10f;
        int[] dataVals = getDataVals();
        float yScale = dataVals[2] / 10f;
        // ordinate
        g2.draw(new Line2D.Double(HPAD, VPAD, HPAD, h - VPAD));
        // tic marks
        float x1 = HPAD, y1 = VPAD, x2 = HPAD - 3, y2;
        for(int j = 0; j < 10; j++)
            g2.draw(new Line2D.Double(x1, y1, x2, y1));
            y1 += yInc;
        // labels
        String text; LineMetrics lm;
        float xs, ys, textWidth, height;
        for(int j = 0; j <= 10; j++)
            text = String.valueOf(dataVals[1] - (int)(j * yScale));
            textWidth = (float)font.getStringBounds(text, frc).getWidth();
            lm = font.getLineMetrics(text, frc);
            height = lm.getAscent();
            xs = HPAD - textWidth - 7;
            ys = VPAD + (j * yInc) + height/2;
            g2.drawString(text, xs, ys);
        // abcissa
        g2.draw(new Line2D.Double(HPAD, h - VPAD, w - VPAD, h - VPAD));
        // tic marks
        x1 = HPAD; y1 = h - VPAD; y2 = y1 + 3;
        for(int j = 0; j < 12; j++)
            g2.draw(new Line2D.Double(x1, y1, x1, y2));
            x1 += xInc;
        // labels
        ys = h - VPAD;
        for(int j = 0; j < 12; j++)
            text = String.valueOf(j + 1);
            textWidth = (float)font.getStringBounds(text, frc).getWidth();
            lm = font.getLineMetrics(text, frc);
            height = lm.getHeight();
            xs = HPAD + j * xInc - textWidth/2;
            g2.drawString(text, xs, ys + height);
        // plot data
        x1 = HPAD;
        yScale = (float)(h - 2*VPAD) / dataVals[2];
        for(int j = 0; j < data.length; j++)
            y1 = VPAD + (h - 2*VPAD) - (data[j] - dataVals[0]) * yScale;
            if(j > 0)
                g2.draw(new Line2D.Double(x1, y1, x2, y2));
            x2 = x1;
            y2 = y1;
            x1 += xInc;
    private int[] getDataVals()
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for(int j = 0; j < data.length; j++)
            if(data[j] < min)
                min = data[j];
            if(data[j] > max)
                max = data[j];
        int span = max - min;
        return new int[] { min, max, span };
}

Similar Messages

  • Draw graph in Origin for assistance Labview

    Hellou,
    I try draw graph in Origin for assistance Labview. In Labview I connect and create new instance Origin template. Template file (.OPJ) was created before. When data is completed in sheet then I draw graph in Origin. But I cant use OA_NewEmptyGraph.vi because is it to create new graph. I try draw graph into to template graph.
    In labview I find for sheets OA_FindWorksheet.vi this is find sheet, but a cant find some "OA_FindGraph.vi" is this exists or realized else?
    Thanks
    Norbert
    Solved!
    Go to Solution.

    Hi Norbert,
    your question seems to be related to LabVIEW, while you have erroneously posted it in the LabWindows/CVI forum...

  • Help||||||||how to draw graphs in java

    dear all
    i m new to the java technology.i am at present working on aproject in which i need to draw graphs.these graphs will show the graphs for past one month,past six month and past one year records display.can u suuggest me where to get the help and how to get the sample sorce code for that.thanx
    regards
    sheetal

    There are a couple of Open Source projects for graphing in Java on Sourceforge, try:
    http://sourceforge.net/projects/jopenchart/
    http://sourceforge.net/projects/jfreechart/
    I haven't used them myself, but I intend to look closer in the future...

  • Draw graph with trackpad?

    hello,
    is any program how to write/draw graph in pages with trackpad? i know that i can make graph in pages but it's slowly...
    thank for tips

    Hello,
    I’m not too sure what the exact problem you are encountering
    is, and I see a sequence structure but I don’t see how it comes in to play
    here.  If your question is about how to
    add multiple plots to an XY graph, I would take a look at the context help
    window which gives good indication about how to add plots to the graph.  Each plot consists of a “bundle” of arrays
    where each element in the bundle is an array of data values.  To add plots to the graph, wire each ‘bundled’
    plot to the “build array” VI.  Make sure
    to expand the plot legend in the graph to account for the multiple plots that
    will be displayed.
    Before troubleshooting the XY graph, I would make sure that
    you are getting the appropriate data from your Data Acquisition device.  Are you certain that you have set up your DAQ
    portion of code correctly, and that the data coming from the device is in the
    proper format?
    Thanks for posting to the forms, please let us know if you have
    any additional information or questions on this.  Have a great weekend!
    Message Edited by Travis M. on 07-21-2006 03:46 PM
    Travis M
    LabVIEW R&D
    National Instruments
    Attachments:
    untitled.JPG ‏68 KB

  • Is apple allow core plot framework to draw graph in iPhone app?

    is apple allow core plot framework to draw graph in iPhone app?

    Wrong forum. Ask in the developer's forum.

  • Drawing Graph in Excel

    I have a template for excel to follow, and I am supposed to draw a graph onto the template using Labview Report Generation Toolkit VIs. However, it keeps returning error  - 2146827284. What am I to check? This error is no longer there whenever i removed all the graph VIs. If I purely just ask Labview to send data to excel at specific locations of excel template, there is no error. Once I initate the plotting of graph, error exists. Do advise.

    The following attachment shows the configuration.
    Attachments:
    help1.JPG ‏117 KB

  • Server Admin not drawing graphs

    I have a fresh install of Leopard that will not display the graphs in Server Admin on the server. I can see the graphs if viewing from my laptop or other machine, but not from the server itself. It gets a few errors like ...
    ... [0x0-0x1b01b].com.apple.ServerAdmin[1734]: * ERROR: -[GRAxes computeLayout]:1124 - plotRect height = 0.000000 <= 0.0 *
    ... [0x0-0x1b01b].com.apple.ServerAdmin[1734]: * ERROR: -[GRChartView computeLayout]:1194 - Layout for overlay axes (0x6826d30) failed. *
    The hardware is a Xserve, 2 x 2.0GHz PPC G5 with 2.0 GB RAM.
    Any help is appreciated as this is an annoying feature.

    Hi
    I see the same "error" messages in every leopard server install I've done - and I've done a fair few - regardless of what hardware was used. Graphs draw fine for me.
    Tony

  • Filter out marked data from XY graph (Draw graph)

    Hi there,
    I've a question about "filtering" data from an XY Graph, please see the attachement.
    The graph shows some sample data (white plot) and a red "ballon" plot (you can press left mouse button
    and move over the graph to draw the red plot).
    My need is to get all samples inside the red ballon, but presently I got stuck with it!
    Any Ideas?!
    (The attached VI is saved by LabVIEW2009 version)
    Solved!
    Go to Solution.
    Attachments:
    Paint_XY_Graph.vi ‏24 KB

    To determine id a point is inside of the red baloon it must satisfy the condition where the X,Y is less than any X,Y point and greater than any other X,Y point.   To filter them out remove outliers from the array or set their values to nan to not plot them 
    Paul Falkenstein
    Coleman Technologies Inc.
    CLA, CPI, AIA-Vision
    Labview 4.0- 2013, RT, Vision, FPGA

  • Drawing graphs in excel sheet using java

    Hi,
    I'm trying to draw a line graph in excel sheet with different segment of the line graph with different colors.I need to accept a Excel file which gives me the details of the location and length of each of these line segments.I need a java code for doing the above.
    Please help me out as this is very urgent and I hv no idea as to how to proceed further.
    Thanking you in advance,
    Vijibindu

    Do a search of this forum for Java and Excel.
    This question has been asked and answered many, many times.
    There's an open source project called POI which should have samples of r
    eading & writing Excel files.
    regards,
    Owen

  • Drawing graphs and repaint issues

    Hi, I'm trying to create a simple scrollable graph. Everything works fine unless I scroll it very slowly or really, really fast. It's all gets messy then - lines to do not seem to be continous, but rather have a lot of empty space. Especially when I press an arrow on the scrollbar and simply hold it - in this case all I get is a bunch of dots.
    It looks like that I'm using an inneficient way to draw the graph (I'm simply using drawLine() method, and repaint() isn't fast enough to redraw everything. Is there another way in Java to make it more efficient?
    Here is my code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.math.*;
    import java.util.*;
    import java.awt.Color;
    public class TestGraph2 extends JFrame{     
    JScrollBar vb = new JScrollBar();
    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER;
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JPanel panel = new JPanel();
    Graph graph = new Graph();
         public TestGraph2() {
              addWindowListener(new WindowAdapter()
              {     public void windowClosing(WindowEvent ev)      
                   {     dispose();               System.exit(0);}});     
    JScrollPane jsp = new JScrollPane(graph, v, h);
    setSize(750,550);     
    getContentPane().setLayout(new GridLayout(1,1));
    getContentPane().add(panel);
    panel.setLayout(new FlowLayout());
    jsp.setPreferredSize(new Dimension(600,500));     
    panel.add(jsp);
    graph.setPreferredSize(new Dimension(4000, 500));
    setVisible(true);                    
         public class Graph extends JPanel
              Graphics2D G;
              public Graph() {
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
         G = (Graphics2D) g;
         G.setColor(Color.white);
         G.fillRect(40,40,graph.getWidth()-80,graph.getHeight()-80);
    int xold=39;
    int xnew=0;
    int yold=graph.getHeight()-39;
    int ynew=0;
              for(int i=39; i<=4000; i=i+10){
              xnew=i;
              int temp = (int)(Math.random() * graph.getHeight()-39);     
              ynew = graph.getHeight()-39-temp;
              if (ynew<39)
                   ynew=39;
              if(ynew>graph.getHeight()-39)
                   ynew=graph.getHeight()-39;
         G.setColor(Color.red);     
              G.drawLine(xold, yold, xnew, ynew);
              xold=xnew;
              yold=ynew;}
    public static void main (String[] args) {     
                                  new TestGraph2();}
         

    Anyone, please?

  • Midlet draw graph

    Hi all,
    for graph drawing i am using below code
    this is working fine if i use limited no of records lik 10 or 20 but if i have 1000 records it not works due
    to double or float data type.drawLine function only support int. if i cast array to int i will not get actual graph
    and even if i have 1000 records thand graph distance is may be 0.2 or 0.3 with mobile screen.
    Is there any solution which i can pass double or float data type to drawLine or if you know suggest some good example please send the example.
    private double store[] = {10.25,15.25,10.35,20.15,15.25,25.15,15.25,10.15,20.15,25.15};
    private void drawGraph(Graphics g)
              g.setColor(0x000000);
                    int gap=(width-(leftGap+rightGap))/store.length;
              int xp=leftGap;    //left gap=25
              for(int i=0;i<store.size();i++)
                        g.drawLine(xp, actValue(store), xp+gap, actValue([i]));
    xp+=1;
         }Thanks and regards.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    {color:red}{size:20px}CROSS POSTED{size}{color}
    [http://forums.sun.com/thread.jspa?threadID=5317122]
    Cross posting is rude.
    db

  • Newbie for plot/draw graph in Java

    Hi everybody:
    I really need help from anyone of you who know the problem that i am facing now. I have all the data in an excel file (.xls). I would like to retireve all the data(all float integers in two coloumn and 300 rows) from this excel file and draw/plot out a graph based on the data in that excel file using java. Can i know how to do that? Is there any available package that i can use? I will be appreciate if there is some sample codes for me. Thank you.
    Serene

    http://jakarta.apache.org/poi/index.html
    http://www.jfree.org/jfreechart/

  • Draw graph with vertices and edges

    Hi, all,
    I'm trying to generate a graph with nodes and edges by using Swing. The problem is I want to generate the graph automatically, which means the program need to know how to put the nodes so the edges among them won't have to cross the nodes. The free software i can find online now can draw nodes and edges, but still need the user to specify the position of the node. Please help me out if you know any such software packages! Thanks a lot in advance!
    J.H.

    you could try
    http://www.utc.edu/~cpmawata/petersen/lesson8.htm
    http://www.ff.iij4u.or.jp/~kanada/ccm/coloring/
    and
    http://student.cosy.sbg.ac.at/~wdietl/study/cs612/Coloring.java
    http://student.cosy.sbg.ac.at/~wdietl/study/cs612/pres.html
    asjf

  • Hyper Draw graph is invisible

    Hi,
    A new bug has come (possible with any Apple update). Sometimes the Hyper draw is invisible. An example is if you select a track, an object, open Piano roll, open Hyper draw for Velocity - you can't see the graph. Or if you change from one object to another - the graph will not update with that objects graph but instead becomes... invisible.
    Any help is appreciated It used to work.
    Best regards,
    Robert

    Do not close the matrix editor window. Each time you open the matrix editor it will resize the layout. You should read the chapter about "Screensets". This way your settings will be saved and you can easily switch between editors.
    Eddie

  • Need API to draw graphs and produce GIF

    Hi. I'm looking for a Java API which will draw 2D graphs, providing some control over things such as axis placement and labelling, and produce a GIF file. I want to call this from within a servlet. So my questions are:
    1. Does "Java 2D" do this? If so, how can I get it?
    2. If no, can anyone recommend a public domain or cheap product?
    Many thanks,
    Peter

    Hi Peter,
    You can use the imageio classes to generate the image graphs. Alternatively you can use java Acme package which is downloadable for free from http://www.acme.com/java/software/ for generating the GIF files.
    Or if you want a charting component you could use JFreeChart.
    There is a lots of amazing things that you can in Java 2D.
    Sathish S.

Maybe you are looking for

  • Error While including the Multisite functionality

    Error While including the Multisite functionality & trying to click on SiteAdministraion tab in BCC Background: We have migrated our application from ATG v9.1 to ATG v 10.0.2 and implementing Multisite on the same Getting this error on BCC console: 1

  • Would like my PDF to open outside of browser.

    Folks, I have a button that opens a PDF file within the browser itself. Is there anyway to force it to open externally (In acrobat outside of the browser). This will be for mass deployment so I would prefer not to have the user do anything other than

  • White square when using Falsh 7.0.14.0

    I use an old program about d-day and the last months of the second world war. There are maps, newspaper reports, photos and also videos on. On the DVD disc is Flash player version 7 included. On my PC is, of course, the latest version of Flash Player

  • "Must-have" Presets for Aperture 3

    Looking for suggestions/recommendations for "must have" presets.  I have a couple from the old MacCreate site (B&W and Color Film presets).  Looking for suggestions/recommendations that rival those available for LR4.

  • How to use BAPI_PROJECT_MAINTAIN to create network activities under WBS elements ?

    Hello ABAPers, I have been using BAPI_PROJECT_MAINTAIN to create Project and WBS elements and I have done them without any errors. Now I need help on how to create network activities. Can anyone share on how to pass data to I_NETWORK table and I_ACTI