I posted this to a reply to my last problem, but figured I should create a new thread for this new problem. As it is quite different.
I am making a simple bar chart, and for some unknown reason, the draw method is being called multiple times (1-3), causing the entire graph's position to change.
How is it calling this method twice? I'll past code below. I put a counter inside of the draw method to see how many times it is being called, and it varies from 1-3. It SHOULD only be called once. So I'm at a complete lost as to why this is happening. Thanks for any help.
import javax.swing.JFrame;;
import java.awt.*;
public class BarGraphDriver
{
public static void main(String[] args)
{
int[] input = {25, 60, 20, 100};//Set height of each bar in the graph (number between 0 and 10
JFrame frame = new JFrame("Bar Graph");
BarPanel panel = new BarPanel(input);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(800, 450);
frame.setBackground(Color.black);
}
}
import javax.swing.JPanel;
import java.awt.*;
public class BarPanel extends JPanel
{
Bar graph;
//--------------------------------------------------------------------------
// Sets up the panel characteristics.
//--------------------------------------------------------------------------
public BarPanel(int[] values)
{
graph = new Bar(values);
}
//--------------------------------------------------------------------------
// Draws the bar
//--------------------------------------------------------------------------
public void paint(Graphics gc)
{
//super.paintComponent(gc);
graph.draw(gc);
}
}
import java.awt.*;
public class Bar
{
private int[] xBar = {10, 10, 60, 60};
private int[] yBar = {300, 100, 100, 300};
private int data[];
private int origData[];
private int count;
public Bar( int initVal[] )
{
data = new int[initVal.length];
origData = new int[initVal.length];
for(int i=0; i<initVal.length; i++)
{
origData[i] = initVal;
data[i] = Math.abs(initVal[i] - 300);
}
}
public void draw(Graphics gc)
{
gc.setColor(Color.RED);
gc.drawLine(10, 301, 600, 301);//horizontal redline
gc.drawLine(10, 301, 10, 10);//vertical redline
for(int h = 0; h<data.length; h++)
{
gc.setColor(Color.GRAY);
gc.drawLine(10, data[h] + 1, 600, data[h] + 1);//horizontal redline
}
for (int i=0; i<data.length; i++) //countes each bar
{
for (int j=0; j<xBar.length; j++)
{
xBar[j] = xBar[j] + 60;
}
if (data[i] >= 1 || data[i] < yBar.length)
{
for(int k = 1; k < 3; k++){
yBar[k] = data[i];
}
}
gc.setColor(Color.BLUE);
gc.fillPolygon(xBar, yBar, yBar.length); // draw bar
int xText = xBar[0];
int yText = data[i] - 10;
gc.setColor(Color.WHITE);
gc.drawString(" " + origData[i], xText, yText);
}
count++;
System.out.print("Count: " + count);
}
}