Tuesday, November 4, 2008

random password in javascript

http://www.javascriptkit.com/script/script2/passwordgenerate.shtml

radom string generator in C# and VB

http://devpinoy.org/blogs/keithrull/archive/2005/03/10/177.aspx

random string generator

http://www.codewalkers.com/c/a/User-Management-Code/random-string-generator-key-generator/

Thursday, October 30, 2008

RandomStringUtils.java

http://www.koders.com/kv.aspx?fid=469723E78254774BEC5E0E17D580B2DA38BA3658

generating random characters

        import java.util.*;

public class Test {

private static Random rn = new Random();

private Test()
{
}

public static int rand(int lo, int hi)
{
int n = hi - lo + 1;
int i = rn.nextInt() % n;
if (i < 0)
i = -i;
return lo + i;
}

public static String randomstring(int lo, int hi)
{
int n = rand(lo, hi);
byte b[] = new byte[n];
for (int i = 0; i < n; i++)
b[i] = (byte)rand('a', 'z');
return new String(b, 0);
}

public static String randomstring()
{
return randomstring(5, 25);
}
}
Actual random numbers are obtained using nextInt(), and then knocked down to the relevant range using the modulo ("%") operator.

Monday, October 20, 2008

Valid characters in URL

Be careful with the characters you use in the OBJECT tag attribute. The set of "safe" characters in a URL is severely restricted by the various ways in which they are transported. According to the standard for URL syntax (Request For Comments 1738), only the following characters are allowed unescaped in URLs, aside from letters of the alphabet and digits:

+  -  =  .  _  /  *      (  )  ,  @  '  $  :  ;  &  !  ?

The special characters used in MINSE have been carefully chosen from this set so that you don't have to "escape" them in URLs (using a percent character and a hexadecimal number). After we set aside the parentheses, the comma, and the characters on the left, which are commonly used in expressions, we are left with just six choices for the macro escape character (the ampersand is inconvenient, because it needs to be represented as an entity; but much worse, far too many browsers are broken and will not parse SGML entities in attribute values). The single-quote was chosen for convenience, because it is a non-shifted key on North-American keyboards.

Anything that is not part of the "safe" character set must always be escaped in a URL. In particular, the percent character ("%") and the space must be escaped. Use the following codes:

for:     space     %
use: %20 %25
Sorry about that, but i can't change the standard. There are good reasons for the decisions made in that document.

Valid characters in URL

URL encoding introduction

link

URL character encoding issues

link

URLs are sequences of characters, i.e., letters, digits, and special
characters. A URLs may be represented in a variety of ways: e.g., ink
on paper, or a sequence of octets in a coded character set. The
interpretation of a URL depends only on the identity of the
characters used.

In most URL schemes, the sequences of characters in different parts
of a URL are used to represent sequences of octets used in Internet
protocols. For example, in the ftp scheme, the host name, directory
name and file names are such sequences of octets, represented by
parts of the URL. Within those parts, an octet may be represented by
the chararacter which has that octet as its code within the US-ASCII
[20] coded character set.

In addition, octets may be encoded by a character triplet consisting
of the character "%" followed by the two hexadecimal digits (from
"0123456789ABCDEF") which forming the hexadecimal value of the octet.
(The characters "abcdef" may also be used in hexadecimal encodings.)

Octets must be encoded if they have no corresponding graphic
character within the US-ASCII coded character set, if the use of the
corresponding character is unsafe, or if the corresponding character
is reserved for some other interpretation within the particular URL
scheme.

No corresponding graphic US-ASCII:

URLs are written only with the graphic printable characters of the
US-ASCII coded character set. The octets 80-FF hexadecimal are not
used in US-ASCII, and the octets 00-1F and 7F hexadecimal represent
control characters; these must be encoded.

Unsafe:

Characters can be unsafe for a number of reasons. The space
character is unsafe because significant spaces may disappear and
insignificant spaces may be introduced when URLs are transcribed or
typeset or subjected to the treatment of word-processing programs.
The characters "<" and ">" are unsafe because they are used as the
delimiters around URLs in free text; the quote mark (""") is used to
delimit URLs in some systems. The character "#" is unsafe and should
always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might
follow it. The character "%" is unsafe because it is used for
encodings of other characters. Other characters are unsafe because
gateways and other transport agents are known to sometimes modify
such characters. These characters are "{", "}", "|", "\", "^", "~",
"[", "]", and "`".

All unsafe characters must always be encoded within a URL. For
example, the character "#" must be encoded within URLs even in
systems that do not normally deal with fragment or anchor
identifiers, so that if the URL is copied into another system that
does use them, it will not be necessary to change the URL encoding.

Reserved:

Many URL schemes reserve certain characters for a special meaning:
their appearance in the scheme-specific part of the URL has a
designated semantics. If the character corresponding to an octet is
reserved in a scheme, the octet must be encoded. The characters ";",
"/", "?", ":", "@", "=" and "&" are the characters which may be
reserved for special meaning within a scheme. No other characters may
be reserved within a scheme.

Usually a URL has the same interpretation when an octet is
represented by a character and when it encoded. However, this is not
true for reserved characters: encoding a character reserved for a
particular scheme may change the semantics of a URL.

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL.

On the other hand, characters that are not required to be encoded
(including alphanumerics) may be encoded within the scheme-specific
part of a URL, as long as they are not being used for a reserved
purpose.





main parts of URL

In general, URLs are written as follows:

:

A URL contains the name of the scheme being used () followed
by a colon and then a string (the ) whose
interpretation depends on the scheme.

Scheme names consist of a sequence of characters. The lower case
letters "a"--"z", digits, and the characters plus ("+"), period
("."), and hyphen ("-") are allowed. For resiliency, programs
interpreting URLs should treat upper case letters as equivalent to
lower case in scheme names (e.g., allow "HTTP" as well as "http").

using secure random and message direct to generate random nad unique number

The following method uses SecureRandom and MessageDigest :

  • upon startup, initialize SecureRandom (this may be a lengthy operation)
  • when a new identifier is needed, generate a random number using SecureRandom
  • create a MessageDigest of the random number
  • encode the byte[] returned by the MessageDigest into some acceptable textual form
  • check if the result is already being used ; if it is not already taken, it is suitable as a unique identifier
The MessageDigest class is suitable for generating a "one-way hash" of arbitrary data. (Note that hash values never uniquely identify their source data, since different source data can produce the same hash value. The value of hashCode, for example, does not uniquely identify its associated object.) A MessageDigest takes any input, and produces a String which :
  • is of fixed length
  • does not allow the original input to be easily recovered (in fact, this is very hard)
  • does not uniquely identify the input ; however, similar input will produce dissimilar message digests
MessageDigest is often used as a checksum, for verifying that data has not been altered since its creation.

Example

import java.security.SecureRandom;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GenerateId {

public static void main (String... arguments) {
try {
//Initialize SecureRandom
//This is a lengthy operation, to be done only upon
//initialization of the application
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");

//generate a random number
String randomNum = new Integer( prng.nextInt() ).toString();

//get its digest
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] result = sha.digest( randomNum.getBytes() );

System.out.println("Random number: " + randomNum);
System.out.println("Message digest: " + hexEncode(result) );
}
catch ( NoSuchAlgorithmException ex ) {
System.err.println(ex);
}
}

/**
* The byte[] returned by MessageDigest does not have a nice
* textual representation, so some form of encoding is usually performed.
*
* This implementation follows the example of David Flanagan's book
* "Java In A Nutshell", and converts a byte array into a String
* of hex characters.
*
* Another popular alternative is to use a "Base64" encoding.
*/

static private String hexEncode( byte[] aInput){
StringBuilder result = new StringBuilder();
char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'};
for ( int idx = 0; idx < aInput.length; ++idx) {
byte b = aInput[idx];
result.append( digits[ (b&0xf0) >> 4 ] );
result.append( digits[ b&0x0f] );
}
return result.toString();
}
}


Example run :

>java -cp . GenerateId
Random number: -1103747470
Message digest: c8fff94ba996411079d7114e698b53bac8f7b037

generate unique ID using UUID utility in Java5

mport java.util.UUID;


public class UniqueID {

public static void main(String args[]){
UUID one = UUID.randomUUID();
UUID two = UUID.randomUUID();

System.out.println(one);

System.out.println(two);



}

}

to generate random characters

link

public class RandomCharacters {

private static void doRandomCharacters() {

double randomNumber;
double randomNumberSetup;
char randomCharacter;

System.out.println("----------------------------------------------------------------------");

for (int i = 0; i < 10; i++) {
randomNumber = Math.random();
randomNumberSetup = (randomNumber * 26 + 'a');
randomCharacter = (char) randomNumberSetup;
System.out.print(randomCharacter + ": ");
switch(randomCharacter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': System.out.print("vowel");
break;
case 'y':
case 'w': System.out.print("sometimes a vowel");
break;
default: System.out.print("consonant");
}
System.out.println(" - Random number was (" + randomNumber + ")");
}

System.out.println("----------------------------------------------------------------------");
System.out.println("\n");
}


/**
* Sole entry point to the class and application.
* @param args Array of String arguments.
*/
public static void main(String[] args) {
doRandomCharacters();
}

}

Thursday, October 16, 2008

what characters are valid in url?

The specification for URLs, RFC1738, limits the use of allowed characters to only a limited subset of the US-ASCII character set (2.2 URL Character Encoding Issues):

"The lower case letters "a"--"z", digits, and the characters plus ("+"), period("."), and hyphen ("-") are allowed.... In addition, octets may be encoded by a character triplet consisting of the character "%" followed by the two hexadecimal digits (from"0123456789ABCDEF") which forming (sic) the hexadecimal value of the octet. (The characters "abcdef" may also be used in hexadecimal encodings.)"

To insert, for example, the French accented à, you would use %E0 instead of the letter.

Tuesday, October 14, 2008

snake game

http://javaboutique.internet.com/Snake/source.html

When the snake game executes it looks like this....click here

parsing a string

study:

You are to create a console application that accepts exactly one command-line argument. If it doesn’t receive the argument, the application must display an error message and exit. The application must parse the text input and output the number of times each letter of the alphabet occurs in the text. Case sensitivity is not required.

For example, if the command-line argument is “baaad” the displayed result must be:

There are 3 A's
There are 1 B's
There are 0 C's
There are 1 D's
There are 0 E's
There are 0 F's
etc...


Result: In this we use Stream Tokenizer.


mport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;


public class Class1 {

public static void main(String[] av) throws IOException {
StreamTokenizer tf = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
String s = null;
char a[] = {'A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z'};

int count = 0;
int i, r=0,m=0;

while ((i = tf.nextToken()) != StreamTokenizer.TT_EOF) {
switch (i) {
/* case StreamTokenizer.TT_EOF:
System.out.println("End of file");
break;
case StreamTokenizer.TT_EOL:
System.out.println("End of line");
break;
case StreamTokenizer.TT_NUMBER:
System.out.println("Number " + tf.nval);
break;*/

case StreamTokenizer.TT_WORD:
s = tf.sval.toUpperCase();
System.out.println("Word, length " + tf.sval.length() + " " );
while(r<>

{if (s.charAt(p) == a[r])

count++;

}

System.out.println("There are " +count +a[r]);

count=0; r++; }

break;

default:

System.out.println("What is it? i = " + i);

} } } }

Thursday, October 9, 2008

requirements for key generator

new class KeyGenerator
lives in a package: edu.gvsu.cri.utils

Research:
1. valid web characters for the url address
2. random key of n characters where n is the parameter of method
3. research methods of randomness i.e. method based on time stand.

Tuesday, September 23, 2008

Code to create a bar and line chart

Code to create bar and line charts both in same frame but in seperate panels. In this we have values on the top of the bars and re-scaling is done using tick units in both charts related to the data present. Two classes 1. MyLineChart and 2. TestMyLineChart


MyLineChart.java

mport javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.LogAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.Range;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import java.awt.*;
import java.text.DecimalFormat;



public class MyLineChart extends JPanel{

/**
*
*/
private static final long serialVersionUID = 1L;

/**
*
*/
//private static final long serialVersionUID = 1L;




public MyLineChart(final String title) {

super();

CategoryDataset dataset = createDataset();
final JFreeChart chart = createChart(dataset);
final JFreeChart chart2 = createChart2(dataset);

CategoryPlot plot = chart2.getCategoryPlot();

BarRenderer renderer = (BarRenderer) plot.getRenderer();
DecimalFormat decimalformat1 = new DecimalFormat("###.0");
renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",decimalformat1));
renderer.setItemLabelsVisible(true);
//double r = renderer.getUpperClip();

//set the range axis to display integers...
final NumberAxis rangeaxis = (NumberAxis) plot.getRangeAxis();

NumberTickUnit tick = new NumberTickUnit(rangeaxis.getUpperBound()/2);
rangeaxis.setTickUnit(tick);

//rangeaxis.getTickLabelFont();




//CategoryAxis domainaxis = plot.getDomainAxis();
//domainaxis.setCategoryMargin(1.0);




//renderer.setItemMargin(0.30);




// this.setLayout(new BorderLayout);
ChartPanel panel = new ChartPanel(chart);
ChartPanel panel2 = new ChartPanel(chart2);
panel.setPreferredSize(new Dimension(400,300));
panel2.setPreferredSize(new Dimension(600,400));
this.add(panel);
this.add(panel2);

}









private CategoryDataset createDataset()
{
String series1 = "First";
String series2 = "Second";
String series3 = "Third";

String category1 = "2001";
String category2 = "2002";
String category3 = "2003";

/*Number number1 = new Integer(20);
Number number2 = new Integer (35);
Number number3 = new Integer (50);*/


DefaultCategoryDataset dataset= new DefaultCategoryDataset();

dataset.addValue(1111.0, series1, category1);
dataset.addValue(4444.0, series1, category2);
dataset.addValue(3333.0, series1, category3);


dataset.addValue(5555.0, series2, category1);
dataset.addValue(7777.0, series2, category2);
dataset.addValue(6666.0, series2, category3);


dataset.addValue(44444.0, series3, category1);
dataset.addValue(333.0, series3, category2);
dataset.addValue(2222.0, series3, category3);

return dataset;

}

private JFreeChart createChart(final CategoryDataset dataset) {

// create the chart...
final JFreeChart chart = ChartFactory.createLineChart(
"Line Chart ", // chart title
"Type", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);


// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
// final StandardLegend legend = (StandardLegend) chart.getLegend();
// legend.setDisplaySeriesShapes(true);
// legend.setShapeScaleX(1.5);
// legend.setShapeScaleY(1.5);
//legend.setDisplaySeriesLines(true);
chart.setBackgroundPaint(Color.white);

final CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(Color.BLACK);
plot.setRangeGridlinePaint(Color.white);


final NumberAxis rangeaxis = (NumberAxis) plot.getRangeAxis();

NumberTickUnit tick = new NumberTickUnit(rangeaxis.getUpperBound()/2);
rangeaxis.setTickUnit(tick);



/*renderer.setSeriesStroke(
0, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {10.0f, 6.0f}, 0.0f
)
);
renderer.setSeriesStroke(
1, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {6.0f, 6.0f}, 0.0f
)
);
renderer.setSeriesStroke(
2, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {2.0f, 6.0f}, 0.0f
)
);
// OPTIONAL CUSTOMISATION COMPLETED.*/

return chart;

}
private JFreeChart createChart2(CategoryDataset dataset) {
final JFreeChart chart2 = ChartFactory.createBarChart(
"Bar Chart", // chart title
"Type", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
false, // tooltips
false // urls
);

return chart2;
}
}




TestMyLineChart.java


import javax.swing.JFrame;



public class TestMyLineChart {

public static void main (String[] args)
{
MyLineChart bar = new MyLineChart("Line and Bar Chart");
JFrame frame = new JFrame("Line Chart");
frame.setVisible(true);
//frame.setLayout(BorderLayout);
frame.add(bar);
frame.setSize(800, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

to change the scale on range axis

I tried to look for a method which directly manipulates the scale on the x-axis but i couldn't find in the ValueAxis class,Number Axis class, Axis class and Category Axis class. Even then i tried different methods but everything went into vain.

Finally i observed tick units. So, when i gave a try with the tick units (number tick units) it worked.
So, i used this method to change the scale on the range axis i.e. I needed only 3 points on the range axis according to the data entered.


final NumberAxis rangeaxis = (NumberAxis) plot.getRangeAxis();

NumberTickUnit tick = new NumberTickUnit(rangeaxis.getUpperBound()/2);
rangeaxis.setTickUnit(tick);



First i entered a reasonable value related to the data in the dataset. But, i wanted a method which calculates the value and places it in the method to re-scale range axis. So, i went through the NumberAxis, Axis, ValueAxis and CategoryAxis methods. But i couldn't find any.

While i know that the method which i am looking for is going to give me an upperbound and i know the method syntax, i was not sure whether it would work with NumberAxis object. I gave it a try and it worked well.

Friday, September 19, 2008

virtual memory low

"virtual memory low".....this was the message i got when have been executing and playing with a program code. The eclipse IDE was shutting down automatically after some time when i tried to execute the program.
I tried to find out the reason for that, i added some code for closing of the frame as i have been working with GUI application in java. I forgot to add that code. Now when i added that, the exe applications were not found in the task manager when the window was closed. Before adding the defaultCloseOperation code, they were visible in the task manager and running.

Thursday, September 18, 2008

to scale the range of the value axis in bar chart

i used
resizeRange(double value) method of ValueAxis class but its of no use.

then tried to use setRangeAboutValue(value,length) but of no use.

i tried to find the method which directly manipulates the scale of the value axis but i couldn't do so.

Tuesday, September 16, 2008

JFreeChart: Bar Chart Demo 7 with a custom item label generator

http://www.java2s.com/Code/Java/Chart/JFreeChartBarChartDemo7withacustomitemlabelgenerator.htm

To insert the value of each bar on top of it

This the code for it....

CategoryPlot plot = chart2.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
DecimalFormat decimalformat1 = new DecimalFormat("##,###.00");
renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",decimalformat1));
renderer.setItemLabelsVisible(true);


When this code was added....nothing happened

renderer.setItemLabelsVisible(true);
chart.getCategoryPlot().setRenderer(renderer)
;


Before setting the item labels visible, you need to first generate the labels by using setItemLabelGenerator, setStandardItemLabelGenerator.
These use decimalformat object to pass the value which handles the data format of the value.





Monday, September 15, 2008

Creating bar chart with trend line

I tried to creat a bar chart and line chart seperately, and then tried to incorporate them in the same panel. But, i couldn't do that as JFreeChart doesn't allow two charts to be in the same panel i.e. ChartPanel. But if you use Component instead of JFreeChart and JPanel instead of ChartPanel you can incorporate both.
But when you use Component instead of JFreeChart you cannot use the ChartFactory class which calls the creatBarchart and createLinechart methods.
As such i couldn't mix the two charts into one using JFreeChart.
But i was able to show to types of charts in one frame and 2 seperate panels.

Thursday, September 11, 2008

changing colors in bar chart

http://forums.sun.com/thread.jspa?messageID=3743082

Customizing JFree chart : Pie Chart

http://balajinatarajan.blogspot.com/2008/04/customizing-jfreechart-pie-chart.html

read and write files

Using Streams to Read and Write Files

File streams are perhaps the easist streams to understand. Simply put, FileInputStream (FileOutputStream) represent an input (output) stream on a file that lives on the native file system. You can create a file stream from the filename, a File object or a FileDescriptor object. Use these streams to read data from or write data to files on the file system.

This small example uses the file streams to copy the contents of one file into another.

import java.io.*;

class FileStreamsTest {
public static void main(String args[]) {
try {
FileInputStream fis = new FileInputStream("farrago.txt");
FileOutputStream fos = new FileOutputStream("outagain.txt");
int c;

while ((c = fis.read()) != -1) {
fos.write(c);
}

fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
}
}






http://telecom.ntua.gr/HTML.Tutorials/java/io/streampairs.html#FILES



}

time series chart

1. first create a time series class. In the constructor of this class, create a series object from TimeSeries class. Then add data to the series object.
2. Now create a dataset object from TimeSeriesCollection class and add the series object to the dataset object.
3. Now create a chart object from JFreeChart class and add the dataset to it.
4. Now add the chart to the panel created.

regarding GUI

When using JPanel for charts: you first create panel (P), then add the chart created previously to the panel (P) and then set the dimensions of the panel or do some graphic stuff for the panel, and finally add the panel to the object where it is being created.
Now in main(): you add the object to the frame which is created before. Then you can observe the chart displayed graphically

Tuesday, September 9, 2008

chart example

http://www.sideofsoftware.com/reports_ChartExample.htm

JFREE RESOURCES...ECLIPSE

http://www.vogella.de/articles/EclipseJFreeChart/article.html

http://www.informit.com/guides/content.aspx?g=java&seqNum=76

http://www.screaming-penguin.com/node/4005

JFree chart tutorial

s a developer, I am often asked to demonstrate new applications. After doing many demos, I noticed that users are often initially more interested in what an application looks like than what it does. I have also noticed that one of the best ways to make a good first impression is with a colorful, three-dimensional chart.

JFreeChart is a popular open source Java charting library that can generate most common chart types, including pie, bar, line, and Gantt charts. In addition, the JFreeChart API supports many interactive features, such as tool tips and zooming. JFreeChart provides an excellent choice for developers who need to add charts to Swing- or web-based applications.

Note: The following examples are based on JFreeChart version 0.9.4. To compile and run the code included with this column, you must have two jar files from the JFreeChart distribution, jfreechart-0.9.4.jar and jcommon-0.7.1.jar, in your classpath.

Charts and datasets
To create a chart using JFreeChart, you must create a Dataset, which you then use to create a JFreeChart. A Dataset contains the data that displays in the chart. JFreeChart features many different Dataset objects, which you can use to create assorted types of charts. Once you create a Dataset, you next create the actual chart. JFreeChart uses an object appropriately named JFreeChart to represent charts. You create JFreeChart objects from Dataset objects with the ChartFactory class. In the following examples, we will create pie, XY, and bar charts along with their corresponding Dataset objects.

Pie chart
A pie chart is created from a PieDataset. The following example creates a PieDataset using the DefaultPieDataset class, adds two values via the setValue() method, and then creates a pie chart with the ChartFactory's createPieChart() method. This example will create a pie chart with the title "Sample Pie Chart," a legend, and two slices: JavaWorld with 75 percent of the pie, and Other with the other 25 percent:

DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("JavaWorld", new Integer(75));
pieDataset.setValue("Other", new Integer(25));

JFreeChart chart = ChartFactory.createPieChart
("Sample Pie Chart", // Title
pieDataset, // Dataset
true // Show legend
);

XY chart
An XYDataset can create area, line, and step XY charts. The following example creates an XYDataset from a series of data containing three XY points. Next, ChartFactory's createAreaXYChart() method creates an area XY chart. In addition to parameters for title, dataset, and legend, createAreaXYChart() takes in the labels for the X and Y axes:

XYSeries series = new XYSeries("Average Size");
series.add(20.0, 10.0);
series.add(40.0, 20.0);
series.add(70.0, 50.0);
XYDataset xyDataset = new XYSeriesCollection(series);

JFreeChart chart = ChartFactory.createAreaXYChart
("Sample XY Chart", // Title
"Height", // X-Axis label
"Weight", // Y-Axis label
xyDataset, // Dataset
true // Show legend
);

Bar chart
A CategoryDataset can create numerous different charts, including horizontal and vertical bar charts. The following example creates a CatagoryDataset with two series of data and two categories, and then creates a 3D vertical bar chart from this dataset. This example creates a chart that compares the sales growth in two quarters over two years:

String[] seriesNames = new String[] {"2001", "2002"};
String[] categoryNames = new String[] {"First Quater",
"Second Quater"};
Number[][] categoryData = new Integer[][] {{new Integer(20),
new Integer(35)},
{new Integer(40),
new Integer(60)}
};
CategoryDataset categoryDataset = new DefaultCategoryDataset
(seriesNames,
categoryNames,
categoryData);

JFreeChart chart = ChartFactory.createVerticalBarChart3D
("Sample Category Chart", // Title
"Quarters", // X-Axis label
"Sales", // Y-Axis label
categoryDataset, // Dataset
true // Show legend
);

Integrate JFreeChart
Integrating JFreeChart into a Swing application is relatively easy. Just create a BufferedImage from the chart and use the image as an icon for a JLabel:

BufferedImage image = chart.createBufferedImage(500,300);

JLabel lblChart = new JLabel();
lblChart.setIcon(new ImageIcon(image));

JFreeChart also includes a class named ChartUtilities that provides several methods for saving charts to files or writing them out to streams in JPEG or PNG format. For example, the following piece of code can export a chart to a JPEG:

ChartUtilities.saveChartAsJPEG(new File("chart.jpg"), chart, 500, 300);

The methods in the ChartUtilities class can be used to create JPEGs for use in a static Webpage, or used in a jsp (JavaServer Pages)/servlet-based application to dynamically stream charts to Webpages.




Another sources:

http://www.developerzone.biz/index.php?option=com_content&task=view&id=36&Itemid=36



Monday, September 8, 2008

ou have to write a manifest file, either using a text editor, or with the "new->untitled text file" option on Eclipse. This is what I wrote
quote:
Manifest-Version: 1.0
Class-Path: java-cup-11a.jar java-cup-11a-runtime.jar
Main-Class: uk.co.critchie.eiffel.test.EiffelFileReader

. . . remembering to put a "return" at the end of the last line.

Then you go through the usual procedure for creating a .jar:
  • Right-click the project in "package" on the left.
  • Export
  • Java->Jar File
  • Click on name of project
  • After the page where it says "packaging"->next
  • Mark the radio button where it says "use existing manifest"
  • Navigate to the manifest file, then "finish"

You need to put all the required files into the directory where the .jar file is.
Bingo. It is all working.

how to import .jar lib files

When using Eclipse, first go to the workspace, then to the current project and then create a new folder called 'lib'. Before doing this, select the jar files from the lib folder of the application (Eg: C:\Documents and Settings\grad-cri\My Documents\NetBeansProjects\JavaLibrary1\lib\jfreechart-1.0.10\jfreechart-1.0.10\lib). And then copy-paste these files in the lib folder in the current project. Now using 'Configure build path' you 'Add JAR' files.
Now, all set.