Thank you, that cleared some confusion up for me. That helped me finish this Bar Chart program.
However, there's one thing I don't understand from here and that is the Graphics2D.
In the BarChart class, I have a method that accepts a parameter of type Graphics2D. In my BarChartComponent class, I create a Graphics2D object by casting g. What I don't quite understand from both of these classes is the need to pass g2 in as an argument for draw.
o_O
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class BarChart
{
public BarChart(int x, int y, int t, int w, String name)
{
xTop = x;
yTop = y;
top = t;
width = w;
title = name;
}
public void draw(Graphics2D g2)
{
Rectangle rect = new Rectangle(xTop, yTop, top, width);
g2.draw(rect);
g2.drawString(title, xTop + 5, yTop + 20);
}
private int xTop;
private int yTop;
private int top;
private int width;
private String title;
}
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class BarChartComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
BarChart myBar1 = new BarChart(0, 0, 420, 30, "Golden Gate");
myBar1.draw(g2);
BarChart myBar2 = new BarChart(0, 40, 159, 30, "Brooklyn");
myBar2.draw(g2);
BarChart myBar3 = new BarChart(0, 80, 215, 30, "Delaware Memorial");
myBar3.draw(g2);
BarChart myBar4 = new BarChart(0, 120, 380, 30, "Mackinac");
myBar4.draw(g2);
}
}
import javax.swing.JFrame;
public class BarChartViewer
{
public static void main(String[] args)
{
BarChartComponent myBar = new BarChartComponent();
JFrame frame = new JFrame();
frame.setSize(500, 200);
frame.setTitle("BarChartViewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(myBar);
frame.setVisible(true);
}
}