What I'm trying to do is make a simple bar graph, with multiple bars of different colors and do this using an array. I create a new bar, set its size and color, and then create another bar, set its size, color and i've also moved it over 10 pixels so its not ontop of the original bar. And I'm using an array for the ractangle shap, and fillrect to fill it.
My problem comes when I add the object to the pane ( frame.getContentPane().add(blue); )
It only adds the last one, it doesn't add the blue bar. does getContentPane repaint the screen or something, so that the previous one doesn't show? Or am I missing something?
Thanks for any input,
Bar Class
import javax.swing.JPanel;
import java.awt.*;
public class Bar extends JPanel
{
private int[] xBar = {25, 25, 30, 30};
private int[] yBar = {350, 100, 100, 350};
private Color fillColor;
public Bar()
{
setBackground(Color.black);
}
public void setSize(int height)
{
yBar[1] = height * 10;
yBar[2] = height * 10;
}
public void changeColor(Color colour)
{
fillColor = colour;
}
public void moveOver(){
for(int i = 0; i < xBar.length;i++)
{
xBar= xBar[i] + 10;
}
}
// Draws the bar
//--------------------------------------------------------------------------
public void paintComponent(Graphics gc)
{
super.paintComponent(gc);
gc.setColor(fillColor);
gc.fillPolygon(xBar, yBar, xBar.length); // draw bar
}
}
BarChart class
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
public class BarChart
{
//--------------------------------------------------------------------------
// Creates the main frame of the program.
//--------------------------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame("Bar Chart");
Bar red = new Bar();
Bar blue = new Bar();
red.setSize(9);
red.changeColor(Color.RED);
blue.moveOver();
blue.setSize(5);
blue.changeColor(Color.BLUE);
frame.getContentPane().add(blue);
frame.getContentPane().add(red);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(400,400);
}
}