Drawing a graph
I've been trying to write program that receives number from user and displays an adjascent number of stars (like a graph) and I want to limit the numbers that can be entered in between 1 and 30. Here's the code I've written but I seem not to arrive at anything close to it.
import java.util.Scanner;
public class Graph
public static void main (String args[])
int counter = 1;
int number =0;
Scanner input = new Scanner(System.in);
while (counter <= 5)
System.out.print("Enter number:");
number = input.nextInt();
if(number <= 1 || number <= 30)
System.out.print("*");
System.out.println();
counter++;
}
In your if statement conditional, you probably want to check that the number is greater than or equal to 1, and you want to AND the two clauses together, not OR them. You'd only print if the number is greater than or equal to 1, and less than or equal to 30 -- that is, if the number is 1-30.
Then you probably want to print the asterisks in a loop.
When you post code, please wrap it in [code][/code] tags, so it's legible.
Similar Messages
-
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. -
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
CJI 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(); -
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 KBI 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 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 -
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 KBAre 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 -
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 -
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!!
RegardssetClipArea 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);
} -
How do i draw a graph in a applet from ny data
Hi, again sorry to keep coming back to you guys, but i have been trying hard to attempt things myself.I have read loads of books and can not find example to work from.I have managed with your "help" to finnish my calculations. Now i need to plot a graph with the data from my X array and Y array. I will then try my self to plot the linear least fit line if it kills me. I would like to print stars on the graph using the points in my arrays. But where do i start
sorry if i am asking to much i will understand if you can't help as you have really good programers asking proper questions instead of a novice like me.i have tried but get errors
LinearLeast1.java:111: illegal start of expression
public void paint (Graphics gr)
^
LinearLeast1.java:120: ';' expected
^
LinearLeast1.java:3: cannot resolve symbol
symbol : class Applet
location: class LinearLeast1
class LinearLeast1 extends Applet
^
3 errors
lindsey
code:
import java.io.*;
class LinearLeast1 extends Applet
{ // start of new class
//defines the sum method
public static double SumA (double arr[])
double SumA =0; //sum of array
if (arr.length >=1)
for(int i=0; i< arr.length; i++)
SumA +=arr;
else
SumA =0; // insuficient data
return SumA;
// defines the sum of XY array method
public static double sumXY (double arrX[],double arrY[])
double SumXY=0; // sum of arrays X*Y
if(arrX.length>=2)
for(int i=0; i< arrX.length;i++)
SumXY +=arrX[i]*arrY[i];
else
SumXY=0;//insufficient data
return SumXY;
//defines the avarage method
public static double AverageB (double arr[])
double SumA =0; //sum of array
double AverageB =0; // average of array
if (arr.length >=1)
for(int i=0; i< arr.length; i++)
SumA +=arr[i];
AverageB = SumA / arr.length;
else
AverageB =0; // insuficient data
return AverageB;
//defines array to the power of 2 method
public static double SumB (double arr[])
double SumB = 0; // sum of squares of array
double SumA =0; //sum of array
double Square =0; // array to the power of 2
if (arr.length >=2)
for(int i=0; i< arr.length; i++)
SumA +=arr[i];
SumB += arr[i] * arr[i];
Square =Math.sqrt((arr.length* SumB - SumA*SumA) / (arr.length*(arr.length-1)));
else
Square =0; // insuficient data
return SumB;
public static void main(String[]args)
{ //start of main method
//values for array x
double [] arrX ={-4.91,-3.84,-2.41,-2.62,-3.78,-0.52,-1.83,-2.01,0.28,1.08,
-0.94,0.59,0.69,3.04,1.01,3.60,4.53,5.13,4.43,4.12};
// values for array y
double [] arrY ={-8.18,-7.49,-7.11,-6.15,-5.62,-3.30,-2.05,-2.83,-1.16,0.52,
0.21,1.73,3.96,4.26,5.75,6.67,7.70,7.31,9.05,10.05};
double SumXY = sumXY(arrX,arrY);
double m = (SumXY-(SumA(arrX)*AverageB(arrY)))/ (SumB(arrX)-(SumA(arrX)*AverageB(arrX)));
double B = LinearLeast1.AverageB(arrY)-m*LinearLeast1.AverageB(arrX);
// System.out.println(" m = "+ m );
// System.out.println(" array X * array Y = "+LinearLeast1.sumXY(arrX,arrY));
// System.out.println(" sum ofarray x "+ LinearLeast1.SumA(arrX));
// System.out.println(" sum ofarray y "+ LinearLeast1.SumA(arrY));
// System.out.println(" avarage of array x " + LinearLeast1.AverageB(arrX));
// System.out.println(" avarage of array y " + LinearLeast1.AverageB(arrY));
// System.out.println(" power of 2 array x " + LinearLeast1.SumB(arrX));
// System.out.println(" m= "+m);
// System.out.println(" B= "+B);
public void paint (Graphics gr)
for(int i=1; i< arr.length; i++)
g.drawLine((i-1)*arrXSCALING, arr[i-1]*YSCALING,
i*XSCALING, arr[i]*YSCALING);
}//end of paint method
} //end of main method
} // end of classThanks for that, I thought I upset every one, only just stopped crying
here is my ammended code again before I go to bed, hope it's right this time
import java.io.*;
class LinearLeast1 extends Applet
{ // start of new class
//defines the sum method
public static double SumA (double arr[])
double SumA =0; //sum of array
if (arr.length >=1)
for(int K=0; K< arr.length; K++)
SumA +=arr[K];
else
SumA =0; // insuficient data
return SumA;
// defines the sum of XY array method
public static double sumXY (double arrX[],double arrY[])
double SumXY=0; // sum of arrays X*Y
if(arrX.length>=2)
for(int K=0; K< arrX.length;K++)
SumXY +=arrX[K]*arrY[K];
else
SumXY=0;//insufficient data
return SumXY;
//defines the avarage method
public static double AverageB (double arr[])
double SumA =0; //sum of array
double AverageB =0; // average of array
if (arr.length >=1)
for(int K=0; K< arr.length; K++)
SumA +=arr[K];
AverageB = SumA / arr.length;
else
AverageB =0; // insuficient data
return AverageB;
//defines array to the power of 2 method
public static double SumB (double arr[])
double SumB = 0; // sum of squares of array
double SumA =0; //sum of array
double Square =0; // array to the power of 2
if (arr.length >=2)
for(int K=0; K< arr.length; K++)
SumA +=arr[K];
SumB += arr[K] * arr[K];
Square =Math.sqrt((arr.length* SumB - SumA*SumA) / (arr.length*(arr.length-1)));
else
Square =0; // insuficient data
return SumB;
public static void main(String[]args)
{ //start of main method
//values for array x
double [] arrX ={-4.91,-3.84,-2.41,-2.62,-3.78,-0.52,-1.83,-2.01,0.28,1.08,
-0.94,0.59,0.69,3.04,1.01,3.60,4.53,5.13,4.43,4.12};
// values for array y
double [] arrY ={-8.18,-7.49,-7.11,-6.15,-5.62,-3.30,-2.05,-2.83,-1.16,0.52,
0.21,1.73,3.96,4.26,5.75,6.67,7.70,7.31,9.05,10.05};
double SumXY = sumXY(arrX,arrY);
double m = (SumXY-(SumA(arrX)*AverageB(arrY)))/ (SumB(arrX)-(SumA(arrX)*AverageB(arrX)));
double B = LinearLeast1.AverageB(arrY)-m*LinearLeast1.AverageB(arrX);
public void paint (Graphics gr)
for(int K=1; K< arr.length; K++)
g.drawLine((K-1)*arrXSCALING, arr[K-1]*YSCALING,
K*XSCALING, arr[K]*YSCALING);
}//end of paint method
} //end of main method
} // end of classHope that is better, I will take your advise and not give up. Will try to have another go tomorrow as it is 2.30am now. So I will try and get some sleep. Thanks again for coming back to answer I needed that bit of encouragement. Don't know if that bit of code for drawing my applet is right or not.
good night and thanks again
Lindsey -
Cannot draw logarithmic graph in Plot Multi-XY vi
Hello All,
I'm trying to use the Plot Multi-XY vi in the picture controls to dynamically draw an X-Y grid on a picture control. I need the grid to be logarithmically scaled, but when I check the "x log?" and "y log" booleans in the cartesian axis attributes to True, nothing at all shows up in the picture. If I un-check those options, I get a nice linear grid. Any help would be greatly appreciated!
Thanks,
JasonHi Ravens Fan,
Here's the VI (taken from an NI Example with just the Cartesian Axis Attributes added and the x and y logs turned to true. If you switch them to false you get a nice graph, but when set to true nothing shows up at all.
Thanks,
Jason
Attachments:
XY Multi Plot Log.vi 15 KB -
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!
VaibhavI 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 -
hi i am doing a portal there i want show the selected row in a bar graph format. is there any format or third party tool so that i can icorporate for drawing graph. nor should i alter my servlets code for it.
hello vijay,
i got one code from google about the drawing of the graph. after seeing that code , i think it will not take the data automatically it should manually.
// BarChart.java
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
* Generic bar chart class with full selection set support.
* @author Melinda Green
public class BarChart extends JPanel {
* implemented by data objects to be charted.
public interface BarValue {
/** specifies the hight (data value) of this bar. */
public float getBarValue();
/** optional summary text suitable for tool-tip or other display.*/
public String getInfoText();
public final static int
SORT_NONE = 0,
SORT_ASCENDING = 1,
SORT_DESCENDING = 2;
public final static int
LINEAR_SCALE = 0,
LOG_SCALE = 1;
private static final int
CHART_LEFT_PAD = 50,
CHART_RIGHT_PAD = 25,
CHART_TOP_PAD = 50,
CHART_BOTTOM_PAD = 50,
CHART_MIN_DIM = 80,
MAX_TIC_LABELS = 10, // greatest number of axis tic labels
TIC_LENGTH = 6, // length of axis tic marks
MIN_BOX_WIDTH_FOR_SEPERATOR = 8; // looks crummy if too small
private final static String NO_VALUES_MSG = "No Bar Values Set";
private static final Color NORMAL_COLOR = Color.blue.darker();
private static final Color HIGHLIGHT_COLOR = Color.yellow;
private String xAxisLabel, yAxisLabel;
private int xScaleType, yScaleType; // log or linear
private SelectionSet selections;
private BarValue barValues[] = null;
private float highVal;
private int anchorSelectionIndex = 0; // base index for range selections
private final Rectangle tmpRect = new Rectangle(); // scratch space
* constructs a BarChart panel.
* @param xAxisLabel - String to draw on x axis - optional.
* @param yAxisLabel - String to draw on y axis - optional.
* @param logScale determines whether to draw x axis on log or linear scale.
* @param sel is an optional SelectionSet. the bar chart class always
* maintains a SelectionSet object which it updates on UI selections.
* callers may call getSelectionSet to monitor BarChart selections and
* to make selection changes which the BarChart will respond to. if
* a non-null SelectionSet parameter is provided here, the BarChart will
* listen to and modify the given one instead.
public BarChart(String xAxisLabel, String yAxisLabel,
int xAxisScaleType, int yAxisScaleType, SelectionSet sel)
this.xAxisLabel = xAxisLabel;
this.yAxisLabel = yAxisLabel;
this.selections = sel == null ? new SelectionSet(BarValue.class) : sel;
setScaleType(Axis.X_AXIS, xAxisScaleType);
setScaleType(Axis.Y_AXIS, yAxisScaleType);
setMinimumSize(new Dimension(
CHART_MIN_DIM + CHART_LEFT_PAD + CHART_RIGHT_PAD,
CHART_MIN_DIM + CHART_TOP_PAD + CHART_BOTTOM_PAD));
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
int b = barAt(me.getPoint().x, me.getPoint().y);
if(b < 0) {
if(!me.isControlDown())
selections.clear(BarChart.this);
repaint();
return;
BarValue selectedBar = barValues;
selections.beginEditing(BarChart.this, false);
if(me.isShiftDown())
selectRange(b, anchorSelectionIndex);
else if(me.isControlDown())
selections.toggle(selectedBar, BarChart.this);
else
selections.setElements(selectedBar, BarChart.this);
if(!me.isShiftDown())
anchorSelectionIndex = b;
selections.endEditing(BarChart.this);
repaint();
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
selectRange(barAt(me.getPoint().x), anchorSelectionIndex);
repaint();
} // end constructor
public void setBarValues(BarValue barValues[], final int sortType) {
this.barValues = new BarValue[barValues.length];
System.arraycopy(barValues, 0, this.barValues, 0, barValues.length);
highVal = Float.MIN_VALUE;
for(int i=0; i<barValues.length; i++)
highVal = Math.max(highVal, barValues.getBarValue());
if (sortType != SORT_NONE) {
Arrays.sort(this.barValues, new Comparator() {
public int compare(Object a, Object b) {
float val1 = ((BarValue)a).getBarValue();
float val2 = ((BarValue)b).getBarValue();
if (sortType == SORT_ASCENDING) {
float tmp = val1;
val1 = val2;
val2 = tmp;
return val2 - val1 > 0 ? 1 : val2 == val1 ? 0 : -1; // NOTE: reverse numeric order
repaint();
} // end setBarValues
public void setScaleType(int axis, int type) {
if( ! (type == LOG_SCALE || type == LINEAR_SCALE))
throw new IllegalArgumentException("BarChart.setScaleType: bad scale type " + type);
if(axis == Axis.X_AXIS)
xScaleType = type;
else
yScaleType = type;
repaint();
* returns the selection set object being used.
* this is either the one provided to the constuctor,
* generated internally otherwise.
public SelectionSet getSelectionSet() {
return selections;
private void selectRange(int b1, int b2) {
if(b1 < 0 || b2 < 0)
return;
selections.clear(BarChart.this);
int range_start = Math.min(b1, b2);
int range_end = Math.max(b1, b2);
for(int i=range_start; i<=range_end; i++)
selections.addElement(barValues[i], BarChart.this);
private void computeBar(int barID, Rectangle rect) {
int chart_width = getWidth() - (CHART_LEFT_PAD+CHART_RIGHT_PAD);
int chart_height = getHeight() - (CHART_TOP_PAD+CHART_BOTTOM_PAD);
int chart_right = CHART_LEFT_PAD + chart_width;
int chart_bottom = CHART_TOP_PAD + chart_height;
rect.height = Math.round(barValues[barID].getBarValue() / highVal * chart_height);
rect.y = CHART_TOP_PAD + (chart_height - rect.height);
if (xScaleType==LINEAR_SCALE) {
rect.width = Math.round(chart_width / (float)barValues.length);
rect.x = CHART_LEFT_PAD + barID * rect.width;
else {
rect.x = 0;
if (barID > 0)
rect.x = Axis.plotValue(barID,
.5f, barValues.length, // value range
CHART_LEFT_PAD, getWidth()-CHART_RIGHT_PAD, // screen range
true, getHeight());
int next = Axis.plotValue(barID+1,
.5f, barValues.length, // value range
CHART_LEFT_PAD, getWidth()-CHART_RIGHT_PAD, // screen range
true, getHeight());
rect.width = next - rect.x;
rect.x += CHART_LEFT_PAD;
public void paint(Graphics g) {
super.paint(g);
Point center = new Point(getWidth()/2, getHeight()/2);
if(g instanceof Graphics2D)
center.x -= stringWidth(NO_VALUES_MSG, g) / 2;
if (barValues == null || barValues.length == 0) {
g.drawString(NO_VALUES_MSG, center.x, center.y);
return;
// draw the data boxes
int lastxend = 0;
int chart_width = getWidth() - (CHART_LEFT_PAD+CHART_RIGHT_PAD);
boolean drawBoxSeperators = chart_width / (float)barValues.length > MIN_BOX_WIDTH_FOR_SEPERATOR;
for(int i=0; i<barValues.length; i++) {
g.setColor(selections.contains(barValues[i]) ? HIGHLIGHT_COLOR : NORMAL_COLOR);
computeBar(i, tmpRect);
if(i == 0)
lastxend = tmpRect.x + tmpRect.width;
else {
if (tmpRect.x > lastxend) {
int diff = tmpRect.x - lastxend;
tmpRect.x = lastxend;
tmpRect.width += diff;
lastxend = tmpRect.x+tmpRect.width;
//System.out.println(tmpRect.x + "," + tmpRect.y + " w=" + tmpRect.width + " h=" + tmpRect.height + " lastxend=" + lastxend);
g.fillRect(tmpRect.x, tmpRect.y, tmpRect.width, tmpRect.height);
g.setColor(Color.gray);
if(drawBoxSeperators && i > 0) // draw a line between each box pair
g.drawLine(tmpRect.x, tmpRect.y, tmpRect.x, tmpRect.y+tmpRect.height);
// draw the axes
g.setColor(Color.black);
Axis.drawAxis(Axis.X_AXIS, MAX_TIC_LABELS, TIC_LENGTH,
.5f, barValues.length, // value range
CHART_LEFT_PAD, getWidth()-CHART_RIGHT_PAD, // screen range
CHART_BOTTOM_PAD, xScaleType==LOG_SCALE, getHeight(), g);
Axis.drawAxis(Axis.Y_AXIS, MAX_TIC_LABELS, TIC_LENGTH,
0, highVal, // value range
CHART_BOTTOM_PAD, getHeight()-CHART_TOP_PAD, // screen range
CHART_LEFT_PAD, yScaleType==LOG_SCALE, getHeight(), g);
Font bold = g.getFont().deriveFont(Font.BOLD);
g.setFont(bold);
if (xAxisLabel != null) {
g.drawString(xAxisLabel, getWidth()-stringWidth(xAxisLabel, g)-20, getHeight()-10);
if (yAxisLabel != null) {
g.drawString(yAxisLabel, CHART_LEFT_PAD-40, 25);
} // end paint
private int barAt(int x, int y) {
if(barValues == null)
return -1;
for(int i=0; i<barValues.length; i++) {
computeBar(i, tmpRect);
if(rectContainsPoint(tmpRect, x, y))
return i;
return -1;
private static boolean rectContainsPoint(Rectangle rect, int x, int y) {
return
rect.x <= x && x <= rect.x+rect.width &&
rect.y <= y && y <= rect.y+rect.height;
private int barAt(int x) {
if(barValues == null)
return -1;
for(int i=0; i<barValues.length; i++) {
computeBar(i, tmpRect);
if(tmpRect.x <= x && x <= tmpRect.x+tmpRect.width)
return i;
return -1;
public static int stringWidth(String str, Graphics g) {
if(g instanceof Graphics2D)
return (int)(g.getFont().getStringBounds(str, ((Graphics2D)g).getFontRenderContext()).getWidth()+.5);
else
return g.getFontMetrics().stringWidth(str);
private static class TestDatum implements BarChart.BarValue {
private int id;
private int dataValue;
public TestDatum(int id, int value) {
this.id = id;
this.dataValue = value;
public int getID() { return id; }
public int getDataValue() { return dataValue; }
public float getBarValue() { return getDataValue(); }
public String getInfoText() { return "id # " + id + ", " + dataValue + " value"; }
* example data. unsorted but will have BarChart perform the sorting.
private final static TestDatum testSamples[] = new TestDatum[] {
new TestDatum(12, 2020),
new TestDatum(88, 2300),
new TestDatum(43, 3001),
new TestDatum(81, 2405),
new TestDatum(10, 2069),
new TestDatum( 2, 2054),
new TestDatum(74, 2339),
new TestDatum(56, 2020),
new TestDatum(57, 2021),
new TestDatum(58, 2023),
new TestDatum(59, 2022),
new TestDatum( 4, 4700),
new TestDatum(98, 3100),
new TestDatum(90, 3454),
new TestDatum(33, 2560),
new TestDatum(99, 2299),
new TestDatum(78, 2020),
new TestDatum(65, 2020),
public static void main(String args[]) {
SelectionSet selections = new SelectionSet(TestDatum.class);
selections.addSelectionSetListener(new SelectionSetListener() {
public void selectionSetChanged(SelectionSet set, Object source) {
System.out.println("main: " + set.getNumElements() + " selected ");
BarChart chart = new BarChart("Number of Samples", "Data Value",
BarChart.LOG_SCALE, BarChart.LINEAR_SCALE, selections);
chart.setBarValues(testSamples, BarChart.SORT_DESCENDING);
JFrame frame = new JFrame("Bar Chart Test");
frame.getContentPane().add(chart);
frame.setSize(new Dimension(500, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} // end class BarChart -
Using g.drawLine to draw a graph
I was wondering if anyone might have some insight as to how to use g.drawLine(x1, y1, x2, y2) to draw the contents of an array to make a graph?
This code shown here just illustrates the idea I'm after.
int a[] = arr;
for( int i = 0; i < a.length; i++ )
g.drawLine(i, arr, i, 300);
The nature of my problem is not being able to get g.drawLine to work in the main, or getting the data from the main to the method. Thanks.public class GraphComponent extends Canvas
private int[] arr;
public GraphComponent(int[] arr)
this.arr=arr;
public void paint(Graphics g)
// Do your paiting here using this.arr array.
public class MyFrame extends Frame
public MyFrame(int[] arr)
this.setLayout(new BorderLayout());
this.add(new GraphComponent(arr));
this.setBounds(10, 10, 400, 300);
public static void main(String[] args)
// Create the array here
MyFrame frame=new MyFrame(args);
frame.setVisible(true);
} -
i am trying to draw a Line 2d graph with a dataset which contains four values like(x,y)(x1,y1)...(x4,y4)
So when i plot the points i couldn't get the (x,y) values since they are very low when compared to other values...
So,is there any way to scale down the graph to the max value of (x,y)
I am using JFreeChart..I can draw graph with given dataset.But theScaling
of the graph is high when a single value ishigh.So
is there any solution to scale down the graph to a
particular value.This sounds very much like you are using JFreeChart.
If so, you might be better off asking in the
JFreeChart forum
http://www.jfree.org/phpBB2/viewforum.php?f=3 ...
I read this as not using JFreeChart! If using JFreeChart than one can just set the range of values to be plotted! -
Regarding draw a graph with zoom speciality
Hi to all,
i have a text file which contains the x,y coordinates of the sinewave.Using these coordinates i need to draw the sinewave graph.Then,i need an option in graph to zoom in and zoom out the graph.How should i do this? kindly post any ideas,if any open source is available please provide me link.i have a text file which contains the x,y coordinates of the sinewave.Whatever for? Can't you just use Math.sin (...)?
Using these coordinates i need to draw the sinewave graph.-- Create a polygon p out of those coordinates.
-- In a paintComponent override, drawPolyline (p.xpoints, p.ypoints, p.npoints)
Then,i need an option in graph to zoom in and zoom out the graph.Apply a scaling factor when creating the polygon. Alternatively, invoke AffineTransformed method createTransformedShape to obtain a scaled polygon.
How should i do this?Your choice, but since you have posted here I thought you intended to do it in Java.
kindly post any ideas,See above.
if any open source is available please provide me link.Isn't this homework? you trying to cheat or what?
db
Maybe you are looking for
-
There are 10 module specific projects. Further map IDs are assigned in all the 10 module projects to have context sensitivity. These are merged into a single project to generate the entire help file. The output for the project is html help (.chm). In
-
MMC hangs on Windows 2008 and SAP MMC console not coming up
Hi All, We are running SAP CRM 7. After upgrading Windows 2003 to Windows 2008 R2, SAP is coming up on our J2ee engine. We are able to login to the SAP J2ee application, but SAP MMC hangs. After the reboot, SAP MMC does come up but it hangs while sta
-
Transfer order printing in release ECC6.0
Hi all. My question is very short. Is it possible to print transfer orders in release ECC 6.0 using smartforms or PDF-forms? I have been checking some SAP notes, and in previous releases the TOs can be printed only in sapscript, but I am not sure if
-
What, you want all that AGAIN? Windows here I come ...
-
HT5262 my phone will not turn on or do anything has anyone else had this problem
I have an iphone 5 and it is barely a year old and it will not come on . it is charged and I have tried to hold the home and sleep button down like it has been suggested to me but it still does not turn on.