File: drawGraph.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class drawGraph
{
public static void main( String args[] )
{
JFrame frame = new JFrame( "Graph" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
CreateGraph createGraph = new CreateGraph();
createGraph.setBackground( Color.WHITE );
frame.add( createGraph );
frame.setSize( 640, 480 );
frame.setVisible( true );
}
}
File: Create Graph.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class CreateGraph extends JPanel
{
public int x (int tx)
{
return (tx + 5);
}
public int y (int ty)
{
return (400 - ty + 5);
}
public void paintComponent( Graphics g )
{
super.paintComponent( g ); // call superclass's paint method
this.setBackground( Color.WHITE );
GraphComponents graphComponents = new GraphComponents();
graphComponents.openFile();
graphComponents.readRecords();
graphComponents.closeFile();
g.setColor( Color.BLACK );
g.drawLine( x(0), y(0), x(620), y(0) );
g.drawLine( x(0), y(0), x(0), y(460) );
g.setColor( Color.BLUE );
for (int i = 0; i < graphComponents.getMaxYCount(); i ++)
{
g.fillRect( x(i*50+10), y(graphComponents.getYValues(i)*20),
40, graphComponents.getYValues(i)*20 );
}
File: GraphComponents.java
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class GraphComponents
{
private Scanner input;
private int yValues [];
private int yCounter;
public GraphComponents ()
{
yValues = new int [10];
yCounter = 0;
}
public void storeYValues (int val)
{
yValues [yCounter++] = val;
}
public int getYValues (int index)
{
return yValues[index];
}
public int getMaxYCount ()
{
return yCounter;
}
public void openFile()
{
try
{
input = new Scanner( new File( ".\\graphvalues.txt" ) );
yCounter = 0;
}
catch ( FileNotFoundException fileNotFoundException )
{
System.err.println( "Error opening file." );
System.exit( 1 );
}
}
public void readRecords()
{
try
{
while ( input.hasNext() )
{
storeYValues (input.nextInt());
System.out.println (yValues[yCounter - 1]);
}
}
catch ( NoSuchElementException elementException )
{
System.err.println( "ERROR: Unable to read file (No such element)" );
input.close();
System.exit( 1 );
}
catch ( IllegalStateException stateException )
{
System.err.println( "ERROR: Unable to read file (State exception)" );
System.exit( 1 );
}
}
public void closeFile()
{
if ( input != null )
input.close();
}
}
Peace ..V,
No comments:
Post a Comment