Problem drawing a graph in Java2D

I am trying to draw a graph using Java2D, onto a JPanel. I works sort of ok, but i have 2 problems;
1. I don't know how to get it "linked" to the paint() method, so everytime someone resizez the window/window looses focus, the drawing is removed.
2. The graphing becomes unacurate when passing more than 25-30 values, I think the problem might be the "hvorPaAkse" (whereOnAksis) or the "okY" (increaseY) value, that for some rasen appear to add too much, so that the error gradually increases for every loop in the for(), or something like that.
I know reading the code and understanding the problem itselv is a challenge, but I if there's anybody out there who can help, I would be thankful for any help!
CODE:
//The draw axis method
public void tegnAkser(JComponent comp, int antX, int antY, int okX, int okY) {
Graphics g = comp.getGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(akseStrek);
g2.draw(new Line2D.Double(origo.x, origo.y, origo.x, comp.getHeight()-((antY*okY)+(comp.getHeight()/yOffset))));
g2.draw(new Line2D.Double(origo.x, origo.y, origo.x+(antX*okX), origo.y));
int hvorPaAkse = origo.x;
System.out.println(comp.getHeight()/antY);
int gangeverdi = 1;
if(comp.getHeight()/antY < 16) {
gangeverdi = 5;
for(int i=0; i<antX; i++) {
g2.draw(new Line2D.Double(hvorPaAkse, origo.y - 2, hvorPaAkse,
origo.y + 2));
g2.drawString("" + i, hvorPaAkse, origo.y + 15);
hvorPaAkse += okX;
hvorPaAkse = origo.y;
for(int i=0; i<antY; i++) {
if(i%gangeverdi == 0) {
g2.draw(new Line2D.Double(origo.x - 2, hvorPaAkse, origo.x + 2,
hvorPaAkse));
g2.drawString("" + i, origo.x - 15, hvorPaAkse);
hvorPaAkse -= okY;
//the drawGraf method
public void tegnGraf(int[] verdier, JComponent comp) {
Graphics g = comp.getGraphics();
Graphics2D g2 = (Graphics2D) g;
int xLengde = comp.getWidth();
int yLengde = comp.getHeight();
origo = new Punkt(xLengde - 9 * (xLengde / xOffset),
yLengde - (yLengde / yOffset));
int ant = verdier.length;
int maxVerdi = 0;
for (int i = 0; i < verdier.length; i++) {
if (verdier[i] > maxVerdi)
maxVerdi = verdier;
tegnAkser(comp, ant+1, maxVerdi+1, (xLengde - (xLengde / xOffset)) / ant,
( (yLengde / yOffset) - yLengde) * -1 / maxVerdi);
g2.setColor(Color.BLUE);
g2.setStroke(grafStrek);
ArrayList punkter = new ArrayList();
for (int i = 0; i < verdier.length; i++) {
g2.drawString("x", origo.x-2 + (i * (xLengde - (xLengde / xOffset)) / ant),
origo.y +3 -
(verdier[i] * ( (yLengde / yOffset) - yLengde) * -1 /
maxVerdi));
punkter.add(new Point2D.Double(origo.x +
(i * (xLengde - (xLengde / xOffset)) / ant),
origo.y -
(verdier[i] *
( (yLengde / yOffset) - yLengde) * -1 /
maxVerdi)
//g2.draw(new Line2D.Double(origo.x,origo.y,origo.x+1,origo.y+1));
for(int i=1; i<punkter.size(); i++) {
Point2D.Double forrige = (Point2D.Double)punkter.get(i-1);
Point2D.Double denne = (Point2D.Double)punkter.get(i);
Line2D.Double linje = new Line2D.Double(forrige,denne);
g2.draw(linje);
Thanks
CJ

I couldn't do much with the code that you posted. It looks like you are plotting integers. Maybe you can use this.
/* Plots plus/minus int values for ordinate for
* evenly-distributed, positive int values on abcissa
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class PlottingIntegers
    public static void main(String[] args)
        int[] data = {
            100, 220, 12, 65, 47, 175, 190, 18
        IntegerPlotter plotter = new IntegerPlotter();
        for(int i = 0; i < 8; i++)
            plotter.plot(data);
JFrame f = new JFrame("Plotting Integers");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(plotter);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
class IntegerPlotter extends JPanel
final int PAD = 25;
List dataList;
public IntegerPlotter()
dataList = new ArrayList();
setBackground(Color.white);
setPreferredSize(new Dimension(400,300));
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int width = getWidth();
int height = getHeight();
int xStep = (width - 2*PAD)/(dataList.size() - 1);
int x = PAD;
int y;
// scale data
int max = ((Integer)Collections.max(dataList)).intValue();
int min = ((Integer)Collections.min(dataList)).intValue();
int vertSpace = height - 2*PAD;
int yOffset = height - PAD;
int yDataOffset = (min >= 0 ? min : max > 0 ? 0 : max);
double scale = (double)vertSpace/(max - min);
int yOrigin = yOffset + (int)(min > 0 ? 0 : max > 0 ? scale*min : - vertSpace);
// draw ordinate
g2.draw(new Line2D.Float(PAD, PAD, PAD, yOffset));
// draw abcissa
g2.draw(new Line2D.Float(PAD, yOrigin, width - PAD, yOrigin));
// label ordinate limits
g2.drawString(String.valueOf(max), 10, PAD - 10);
g2.drawString(String.valueOf(min), 10, yOffset + PAD/2);
g2.setStroke(new BasicStroke(4f));
g2.setPaint(Color.red);
for(int i = 0; i < dataList.size(); i++)
y = yOrigin -
(int)(scale * (((Integer)dataList.get(i)).intValue() - yDataOffset));
g2.draw(new Line2D.Float(x, y, x, y));
x += xStep;
protected void plot(int input)
dataList.add(new Integer(input));
repaint();

Similar Messages

  • I DRAW A GRAPH IN 2D AND I HAVE A PROBLEME WITH THE BUBBLE HELP(ToolTipText

    dear friend,
    i wrote a java applet that draws a graph in 2D. i want to have coordinates (x,y) on an bubble help while displacing the mouse on the graph.
    if someone have an idea, thank you to rather communicate it to me as soon as possible.
    thanks.

    I don't think you can use a tooltip in this case.
    You need to add a MouseMotionListener, then follow the mousemove and build you own TollTip.
    Noah

  • Using appended array to draw a graph

    Hi Guys, I'm having a problem with using appended array. I used appended array to save the values from the analyser and then use those values to draw a graph. I have attached 2 VI with this post.  
                                   1st-I can able to save the results in the appended array in different rows.                               2nd-I couldn't save the results in different rows. I can able to save the results in one row only. The new results are over write on the same row.  Can anyone help me with this please? RegardsMayuren  
    Attachments:
    15.vi ‏63 KB
    new1.vi ‏13 KB

    I have attached the sub VI for the previous post
    Attachments:
    Append Text Strings.vi ‏17 KB
    Concatenate Strings.vi ‏15 KB
    Multi-Line List to Array of Strings.vi ‏44 KB

  • How to draw xy graph with multiple y axis input?

    Hi,
    I have problem in xy graph, the xy graph only can show 1 signal from the y axis input ( As you can see in the attachment )
    Is it possible to draw xy graph with 2 Y input? Or maybe there are another type of graph that possible to do this? 
    Note:  the x axis should be from an input too ( not versus time / sample ).
    All answer and advice are welcomed.
    Best regards,
    Alvin Chandra 
    Solved!
    Go to Solution.
    Attachments:
    Example.vi ‏139 KB

    Are you asking for a second Y scale on the graph?
    If so, right click on the existing scale, select "Duplicate Scale". This will create a second scale. You can then (if you wish), right click on the new scale a select "Swap Sides" to put it on the other side of the graph.
    Are you asking about adding a second plot?
    If so then you need to bundle your arrays of X and Y points into clusters and build those into an array:
    The X-axis is always from an input on the XY Graph. You just need to change the axis title. Easiest way to do this is to double click on the axis title and type the new name.
    Rob

  • Need help to draw a graph from the output I get with my program please

    Hi all,
    I please need help with this program, I need to display the amount of money over the years (which the user has to enter via the textfields supplied)
    on a graph, I'm not sure what to do further with my program, but I have created a test with a System.out.println() method just to see if I get the correct output and it looks fine.
    My question is, how do I get the input that was entered by the user (the initial deposit amount as well as the number of years) and using these to draw up the graph? (I used a button for the user to click after he/she has entered both the deposit and year values to draw the graph but I don't know how to get this to work?)
    Please help me.
    The output that I got looked liked this: (just for a test!) - basically this kind of output must be shown on the graph...
    The initial deposit made was: 200.0
    After year: 1        Amount is:  210.00
    After year: 2        Amount is:  220.50
    After year: 3        Amount is:  231.53
    After year: 4        Amount is:  243.10
    After year: 5        Amount is:  255.26
    After year: 6        Amount is:  268.02
    After year: 7        Amount is:  281.42
    After year: 8        Amount is:  295.49
    After year: 9        Amount is:  310.27
    After year: 10        Amount is:  325.78
    After year: 11        Amount is:  342.07
    After year: 12        Amount is:  359.17
    After year: 13        Amount is:  377.13
    After year: 14        Amount is:  395.99
    After year: 15        Amount is:  415.79
    After year: 16        Amount is:  436.57
    After year: 17        Amount is:  458.40And here is my code that Iv'e done so far:
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.Math;
    import java.text.DecimalFormat;
    public class CompoundInterestProgram extends JFrame implements ActionListener {
        JLabel amountLabel = new JLabel("Please enter the initial deposit amount:");
        JTextField amountText = new JTextField(5);
        JLabel yearsLabel = new JLabel("Please enter the numbers of years:");
        JTextField yearstext = new JTextField(5);
        JButton drawButton = new JButton("Draw Graph");
        public CompoundInterestProgram() {
            super("Compound Interest Program");
            setSize(500, 500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            amountText.addActionListener(this);
            yearstext.addActionListener(this);
            JPanel panel = new JPanel();
            panel.setBackground(Color.white);
            panel.add(amountLabel);
            amountLabel.setToolTipText("Range of deposit must be 20 - 200!");
            panel.add(amountText);
            panel.add(yearsLabel);
            yearsLabel.setToolTipText("Range of years must be 1 - 25!");
            panel.add(yearstext);
            panel.add(drawButton);
            add(panel);
            setVisible(true);
            public static void main(String[] args) {
                 DecimalFormat dec2 = new DecimalFormat( "0.00" );
                CompoundInterestProgram cip1 = new CompoundInterestProgram();
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.getContentPane().add(new GraphPanel());
                f.setSize(500, 500);
                f.setLocation(200,200);
                f.setVisible(true);
                Account a = new Account(200);
                System.out.println("The initial deposit made was: " + a.getBalance() + "\n");
                for (int year = 1; year <= 17; year++) {
                      System.out.println("After year: " + year + "   \t" + "Amount is:  " + dec2.format(a.getBalance() + a.calcInterest(year)));
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   // TODO Auto-generated method stub
    class Account {
        double balance = 0;
        double interest = 0.05;
        public Account() {
             balance = 0;
             interest = 0.05;
        public Account(int deposit) {
             balance = deposit;
             interest = 0.05;
        public double calcInterest(int year) {
               return  balance * Math.pow((1 + interest), year) - balance;
        public double getBalance() {
              return balance;
    class GraphPanel extends JPanel {
        public GraphPanel() {
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.red);
    }Your help would be much appreciated.
    Thanks in advance.

    watertownjordan wrote:
    http://www.jgraph.com/jgraph.html
    The above is also good.Sorry but you need to look a bit more closely at URLs that you cite. What the OP wants is a chart (as in X against Y) not a graph (as in links and nodes) . 'jgraph' deals with links and nodes.
    The best free charting library that I know of is JFreeChart from www.jfree.org.

  • My problem is the graphs of my audio recordings in the arrange window are so small it makes accurate editing very difficult.

    My problem is the graphs of my audio recordings in the arrange window are so small it makes accurate editing very difficult.

    Try the waveform zoom slider. Recording louder just to get a better visible waveform would be, well, silly.
    From the manual: (click on links to see pics)
    To change the zoom level using the Waveform Zoom button 
    Click-hold the Waveform Zoom button. A slider appears.
    http://documentation.apple.com/en/logicpro/usermanual/Art/S01/S0185_WaveZoom.png
    Drag the slider. As you do, the waveform shown in all audio regions, and in the Beat Mapping track, is increased or decreased in size.
    http://documentation.apple.com/en/logicpro/usermanual/Art/S09/S0931_CUS_Waveform Zoom2.png 
    Note: This is a purely visual function. The amplitude (level) of the waveform is not affected.
    it's here (scroll 3/4 down):
    http://documentation.apple.com/en/logicpro/usermanual/index.html#chapter=4%26sec tion=6%26tasks=true

  • Work book migration problem : error in graph

    Hi all,
    I have a work book ,created in 3.x ...now we are on 7.0 So when iam migrating i got error .
    I have resolved  other errors..but one error is remained , problem with the graph....
    on X axis with values it is showing header row also..how can i avoid header row...? to not display in graph....
    As data table  source controlled by BI  so ia mnotable to maintain range for graph....
    Problem is when it is with out scalling factors it is displaying correctly in graph also..
    When iam selecting option to display scalling factor it is showing header row also in graph... coz of that graph was showing wrong data...
    cal day    Quantity
    above is with out scalling factor display..everything correct
    blank     Quantity
    cal day       KG
    When iam selecting scalling factor sys will add one more row to display... this is the problem sys did not set automaticaly to consider or to leave first 2 rows...
    How can resolve...? In 3.X it is working fine...... (There is no macro )
    Thanks
    BK
    Edited by: BK BI on Jun 8, 2010 8:56 AM

    Hi,
    Go to the workbook in development system. Find out the technical name of the workbook ( in query designer you wil find in properties).
    Copy it and go to the production system. Assign it to the required role you want. It will be visible in the perticular role in production.
    I would still suggest if possible transport the role from dev to prod. (to keep all systems in line with each other)
    Hope this helps.
    Regards,
    Viren

  • How to draw an arrow in Java2D ?

    Hi ,
    Can anybody tell me how can I draw an arrow in Java2D ? The main issue here is to draw the 2 small arrow lines at the appropriate angle at one end of the line
    Thanks
    Ratheesh

    import java.awt.*;
    import java.awt.geom.*;
    public abstract class Transformers
    extends Component {
    Shape mAxes, mShape;
    int mLength = 54, mArrowLength = 4, mTickSize = 4;
    public Transformers() {
    mAxes = createAxes();
    mShape = createShape();
    protected Shape createAxes() {
    GeneralPath path = new GeneralPath();
    // Axes.
    path.moveTo(-mLength, 0);
    path.lineTo(mLength, 0);
    path.moveTo(0, -mLength);
    path.lineTo(0, mLength);
    // Arrows.
    path.moveTo(mLength - mArrowLength, -mArrowLength);
    path.lineTo(mLength, 0);
    path.lineTo(mLength - mArrowLength, mArrowLength);
    path.moveTo(-mArrowLength, mLength - mArrowLength);
    path.lineTo(0, mLength);
    path.lineTo(mArrowLength, mLength - mArrowLength);
    // Half-centimeter tick marks
    float cm = 72 / 2.54f;
    float lengthCentimeter = mLength / cm;
    for (float i = 0.5f; i < lengthCentimeter; i += 1.0f) {
    float tick = i * cm;
    path.moveTo( tick, -mTickSize / 2);
    path.lineTo( tick, mTickSize / 2);
    path.moveTo(-tick, -mTickSize / 2);
    path.lineTo(-tick, mTickSize / 2);
    path.moveTo(-mTickSize / 2, tick);
    path.lineTo( mTickSize / 2, tick);
    path.moveTo(-mTickSize / 2, -tick);
    path.lineTo( mTickSize / 2, -tick);
    // Full-centimeter tick marks
    for (float i = 1.0f; i < lengthCentimeter; i += 1.0f) {
    float tick = i * cm;
    path.moveTo( tick, -mTickSize);
    path.lineTo( tick, mTickSize);
    path.moveTo(-tick, -mTickSize);
    path.lineTo(-tick, mTickSize);
    path.moveTo(-mTickSize, tick);
    path.lineTo( mTickSize, tick);
    path.moveTo(-mTickSize, -tick);
    path.lineTo( mTickSize, -tick);
    return path;
    protected Shape createShape() {
    float cm = 72 / 2.54f;
    return new Rectangle2D.Float(cm, cm, 2 * cm, cm);
    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    // Use antialiasing.
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    // Move the origin to 75, 75.
    AffineTransform at = AffineTransform.getTranslateInstance(75, 75);
    g2.transform(at);
    // Draw the shapes in their original locations.
    g2.setPaint(Color.black);
    g2.draw(mAxes);
    g2.draw(mShape);
    // Transform the Graphics2D.
    g2.transform(getTransform());
    // Draw the shapes in their new locations, but dashed.
    Stroke stroke = new BasicStroke(1,
    BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
    new float[] { 3, 1 }, 0);
    g2.setStroke(stroke);
    g2.draw(mAxes);
    g2.draw(mShape);
    public abstract AffineTransform getTransform();
    public Frame getFrame() {
    ApplicationFrame f = new ApplicationFrame("...more than meets the eye");
    f.setLayout(new BorderLayout());
    f.add(this, BorderLayout.CENTER);
    f.setSize(350,200);
    f.center();
    return f;
    }

  • How to draw a graph step by step ?

    Hi, sirs,
    Can you tell me how to draw a graph step by step by using Labview 6.0 ? On one step, I create two variables : one variable is used for X-axis, and other variable is used for Y-axis. Can you give me a simple example ?
    Thanks a lot.

    Try this example out.
    Attachments:
    plotxy.vi ‏24 KB

  • Could you please give me the method to draw Line Graph in detail?

    Could you please give me the method to draw Line Graph in detail?

    Hi,
    First update your username instead of using that number.
    and also provide full information like
    Apex version
    Database version
    I am giving you one link related to charts,
    http://dgielis.blogspot.in/2011/02/apex-4-bug-series-type-bar-line-marker.html
    Hope this will helps you
    Thanks and Regards
    Jitendra

  • Problems drawing image

    Im sorry for even askign this but i'm having problems drawing an image, no idea why its not working!!! I know that my Image object actually is the image because i can get it to display on a button, but i need to get it to display in the JPanel through the paintComponent() method, for some reason it wont do it. Thanks for the help.
    Here's my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class StatWindow extends JDialog{
        private StatPanel panel;
        public StatWindow(JFrame parent) {
            this(parent, null);
        public StatWindow(JFrame parent, String data){
            super(parent, "Stat", false);
            getContentPane().setLayout(null);
            panel = new StatPanel();
            getContentPane().add(panel);
            panel.setBounds(0, 0, 220, 220);
            setSize(300, 300);
            setVisible(true);
        class StatPanel extends JPanel{
            private Image diagram1;
            private Image diagram2;
            private Image diagram3;
            private Image diagram4;
            private Image diagram5;
            private Image diagram6;
            private Image diagram7;
            private Image diagram8;
            private Image diagram9;
            private Image diagram10;
            private Image diagram11;
            private Image diagram12;
            private Image diagram13;
            private Image diagram14;
            private Image diagram15;
            private Image diagram16;
            private Image diagram17;
            private Image diagram18;
            private Image diagram19;
            private Image diagram20;
            private Image diagram21;
            private Image diagram22;
            private Image diagram23;
            private Image diagram24;
            private Image diagram25;
            private Image diagram26;
            private Image diagram27;
            public StatPanel(){
                super();
                Image diagram1 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_01.jpg"));
                Image diagram2 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_02.jpg"));
                Image diagram3 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_03.gif"));
                Image diagram4 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_04.jpg"));
                Image diagram5 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_05.jpg"));
                Image diagram6 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_06.jpg"));
                Image diagram7 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_07.gif"));
                Image diagram8 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_08.jpg"));
                Image diagram9 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_09.jpg"));
                Image diagram10 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_10.jpg"));
                Image diagram11 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_11.gif"));
                Image diagram12 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_12.jpg"));
                Image diagram13 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_13.jpg"));
                Image diagram14 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_14.gif"));
                Image diagram15 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_15.gif"));
                Image diagram16 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_16.jpg"));
                Image diagram17 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_17.jpg"));
                Image diagram18 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_18.gif"));
                Image diagram19 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_19.jpg"));
                Image diagram20 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_20.jpg"));
                Image diagram21 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_21.jpg"));
                Image diagram22 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_22.gif"));
                Image diagram23 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_23.jpg"));
                Image diagram24 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_24.gif"));
                Image diagram25 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_25.jpg"));
                Image diagram26 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_26.jpg"));
                Image diagram27 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_27.jpg"));
                addMouseMotionListener(new MouseMotionHandler());
                addMouseListener(new MouseHandler());
                JButton b = new JButton(new ImageIcon(diagram1));
                getContentPane().add(b);
                b.setBounds(0, 0, 40, 40);
            class MouseMotionHandler extends MouseMotionAdapter{
                public void mouseMoved(MouseEvent e){
            class MouseHandler extends MouseAdapter{
                public void mousePressed(MouseEvent e){
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g.create();
                g2d.drawImage(diagram1, 0, 0, this);
                g2d.dispose();
    }

    you have these declarations
    private Image diagram1;
    private Image diagram2;
    and in your constructor you have these
    Image diagram1 = getToolkit().getImage...
    Image diagram2 = getToolkit().getImage...
    the inclusion of the 'type' Image makes them local to the constructor

  • Easiest Way to draw a graph

    Hi guys,
    what is the easiest way to draw a graph in java?
    Suppose I have 2 arrays. One array contains the x-coordinates. Another array contains the respective y-coordinates.
    I do not need the graph to be smooth. Is there a API in java that allows the programmer to draw a graph simply? If not, please kindly advise what would be the easiest way to do it. I do not need the codes but just some suggestions and advice will be fine.
    Many thanks for your time and attention!!
    Regards

    setClipArea and drawPolyline <--- good ideas, however, say 'thank you' and soon please. I did this app for someone at these forums a few months back - a line graph applet with labels etc - try it;-import java.awt.*;
    public class LineGraff extends java.applet.Applet{
       double []toGraff = {6.0, -14.0, -164.0, -210.0, 108.0, 770.0,
                                1354.0, 896.0, -572.0, -1348.0, -780.0, -108.0};
       double []numsFromFile = {6.0, -14.0, -164.0, -210.0, 108.0, 770.0,
                                1354.0, 896.0, -572.0, -1348.0, -780.0, -108.0};
       int max, min, size, Hscale;
       double Vscale;
       public void init(){
          size = numsFromFile.length-1;
          java.util.Arrays.sort(numsFromFile);
          max = (int) numsFromFile[size];
          min = (int) numsFromFile[0];
          Vscale = max-min;
          Vscale = 200/Vscale;
         Hscale = Math.round(300/size);
       public void paint(Graphics g) {
          g.setFont(new Font("Arial",0,14));
          g.drawString("Example app: drawing a graph from a double array",25,18);
          g.setFont(new Font("Arial",0,10));
          g.setColor(Color.blue);
          g.fillRect(10,20,365,230);
          g.setColor(Color.cyan);
          g.drawLine(25,25,25,225);
          g.drawLine(25,140,330,140);
          g.setColor(Color.white);
          int intA = 30, intB = 0, intC = 0;
          int intD = (int) (Math.round(140 - (Vscale * toGraff[0])));
             for(int i=1; i <= size; i++) {
               intC = intA + Hscale;
               intB = intD;
               intD = (int) (Math.round(140 - (Vscale * toGraff[ i ])));
               g.drawLine(intA, intB, intC, intD);
                  if(toGraff[ i ] > 0)
                     g.drawString(Double.toString(toGraff[ i-1 ]), intA+6, intB-3);
                  else
                     g.drawString(Double.toString(toGraff[ i-1 ]), intA+6, intB+8);
               intA += Hscale;
          g.drawString(Double.toString(toGraff[size]), intA+6, intD-3);    
    }

  • Pain problems with a graph

    Hi
    I have a 2D Array and and i am using the paint function to
    draw a graph. T
    I need to draw the axis of the graph but i am finding this difficult,
    1. I cannot pass the 2D array to the public void paint ()method
    2. I do not know how to write the axis they should be in the first part
    of the array
    String [][] otherFrameData;
    barChart(String [][] Data)
    otherFrameData= Data;
    setTitle("Graph Chart");
    setSize(400,350);
    setVisible(true);
    public void paint(Graphics g)
    int x = 50;
    int y = 300;
    int width = 20;
    int gap = 5;
    //The Axis
    g.drawLine(x,y,x+ otherFrameData.length*(width+gap),y);
    g.drawLine(x,y,x,30);
    //Labelling the axis
    for (int i=0; i < otherFrameData.length; i++)
    g.drawString(otherFrameData[0][0],i*(width+gap)+gap+x,y+20);
    Can someone please help me make the 2D array available to public void paint()
    and how to write the axis names the firs part of the array are months
    as i am very confused as to how to get this working
    Cheers

    Very simple example goes like this (since that is homework, I didn't document the code ...):
    import java.awt.*;
    import javax.swing.*;
    import java.awt.font.*;
    public class Chart
        public static void main(String args[])
         final JPanel contentPane = new JPanel(new BorderLayout());
         contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
         contentPane.add(new JLabel("A Chart"), BorderLayout.NORTH);
         contentPane.add(new ChartPanel(new int[]{50, 100, 75, 82}), BorderLayout.CENTER);
         final JFrame frame = new JFrame("Chart");
         frame.setContentPane(contentPane);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(640, 480);
         frame.setVisible(true);
        static class ChartPanel extends JComponent {
         private final static String[] months = {"Jan", "Feb", "Mar", "Apr"};
         private int[]  rainfall;
         public ChartPanel(int[] rainfall) {
             this.rainfall = rainfall;
         public void paint(Graphics g) {
             FontRenderContext frc;
             if (g instanceof Graphics2D) {
              frc = ((Graphics2D)g).getFontRenderContext();
             } else {
              frc = new FontRenderContext(new java.awt.geom.AffineTransform(), false, false);
             int maxRainFall = Integer.MIN_VALUE;
             for (int i = 0; i < rainfall.length; i++) {
              if (rainfall[k] > maxRainFall) {
                  maxRainFall = rainfall[k];
             maxRainFall += 10 - (maxRainFall % 10);
             final int xOff = 20;
             int x = xOff;
             TextLayout tl;
             final Font font = g.getFont();
             final float[][] textData = new float[months.length][2];
             float minAdvance = Float.MAX_VALUE;
             float maxAdvance = Float.MIN_VALUE;
             float maxAscent  = Float.MIN_VALUE;
             float maxDescent = Float.MIN_VALUE;
             for (int k = 0; k < months.length; k++) {
              tl = new TextLayout(months[k], font, frc);
              final float advance = tl.getAdvance();
              final float ascent  = tl.getAscent();
              final float descent = tl.getDescent();
              if (ascent > maxAscent) {
                  maxAscent = ascent;
              if (advance > maxAdvance) {
                  maxAdvance = advance;
              if (advance < minAdvance) {
                  minAdvance = advance;
              if (descent > maxDescent) {
                  maxDescent = descent;
             final int y = maxRainFall + 12 + (int)maxAscent;
             final int offset1 = Math.max((int)minAdvance - 5, 4) / 2;
             final int offset2 = (int)maxAdvance + 10;
             for (int k = 0; k < months.length; k++) {
              g.drawString(months[k], x, y);
              final int height = rainfall[k];
              g.drawRect(x + offset1, y-12-height-(int)maxAscent, 5, height);
              x += offset2;
             int lineX1 = 0;
             int lineX2 = xOff+x;
             int lineY1 = y-6-(int)maxAscent;
             int lineY2 = lineY1;
             g.drawLine(lineX1, lineY1, lineX2, lineY2);
             lineX1 = xOff/2;
             lineX2 = lineX1;
             lineY1 = y+(int)maxDescent;
             lineY2 = 0;
             g.drawLine(lineX1, lineY1, lineX2, lineY2);
    }

  • Problem drawing an arrow

    i am facing serious problems drawing an arrow which has to be moved round the screen.
    does anybody have any idea or reference websites that would solve my problem
    i have to rotate the arrow to the mouse pointer to wherever it is dragged.
    hope u will get with this nick
    hussain52

    A more descriptive backgound to the problem may help people come up with a solution for you.
    From what you've said it sound like you need to use a canvas and paint the arrow on it. Then use a mouse listener to listen for mouse clicks on the arrow and re-draw the arrow appropriatly.
    Does this sound like it might work?
    If so, try the code below...
    It only paints a line, but it might get you thinking in the right direction?
    Additions to get it to do what you want are...
    1. Draw an arrow head at the end of the line.
    2. Listen for mouse clicks within a certain radius of the end of the line.
    3. Redraw the line using the original start point and the new end.
    However, if I've completely missunderstood then it's all a complete waste of time.... but I've enjoyed it.
    Adios amigo.
    /*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Class declaration
    * @author Ollie Lord
    * @version %I%, %G%
    public class ArrowCanvas extends Canvas implements MouseListener {
    private int startX;
    private int startY;
    private int endX;
    private int endY;
    * Constructor declaration
    * @see
    public ArrowCanvas() {
              setSize(new Dimension(200, 200));
              addMouseListener(this);
    public void paint(Graphics g) {
              g.setColor(Color.black);
              g.drawLine(startX, startY, endX, endY);
    * Invoked when the mouse has been clicked on a component.
    public void mouseClicked(MouseEvent e) {
    * Invoked when the mouse enters a component.
    public void mouseEntered(MouseEvent e) {
    * Invoked when the mouse exits a component.
    public void mouseExited(MouseEvent e) {
    * Invoked when a mouse button has been pressed on a component.
    public void mousePressed(MouseEvent e) {
              System.out.println("Pressed");
              startX=e.getX();
              startY=e.getY();
    * Invoked when a mouse button has been released on a component.
    public void mouseReleased(MouseEvent e) {
              System.out.println("Released");
              endX=e.getX();
              endY=e.getY();
              repaint();
    * Method declaration
    * @param args
    * @see
    public static void main(String[] args) {
    JFrame frame = new JFrame("Arrow");
    frame.getContentPane().add(new ArrowCanvas());
    frame.pack();
    frame.show();
    /*--- formatting done in "Ollies Java Convention" style on 07-04-2001 ---*/

  • How to draw a graph of tree structure (using shapes and lines)?

    Hello,
    I tried to search this solution in the forum, and I see people asking and replying with solutions to similar situation, but I don't get what I am looking for. Also because I have never tried with graphs before.
    So, my problem is, I need a function that takes a string with tree structure, as in automata or tree graph, and displays the nodes in tree form. "Tree" is not important, but important is that each object should be displayed as a node and lines connecting them. Please see the image below (with three possible options):
    So, basically, the tree structure could be like X(a, X(a,b), c) where X(a,b) is a sub-tree of higher level X. The program knows the parent-child relationship, so this function only needs to display those elements in a graphical fashion.
    I pass the string in the form of a 2D array showing the hierarchy (to simplify).
    In the image, I am showing three possible options for showing the tree. The third option eliminates those circles and rectangles, if that simplifies.
    I hope I explained clearly.
    Thanks ahead!
    Vaibhav

    I would start drawing from the top. The nodes will be the easy part.
    Begin with the root node centered in the drawing area horizontally and against the top of the drawing area. The second row of nodes would be located vertically (as in my example) 1.5x pixels below the first one, and either distributed horizontally across the available drawing area or at a fixed distance - like 1.5x again, or someother distance you define.
    The tricky part will be drawing the lines since they need run between the edges of nodes. This is where the high-school geometry might come in.
    Keep us posted on what you come up with. Extra points for coming up with a solution that will automatically resize itself to fit the available drawing area! (I've already given you all the clues for how to do that too.)
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

Maybe you are looking for