So I'm trying to change the paint method from the Canvas class to accept an array as one of the parameters. This is what I tried:
int[] array = createArray(10, 1, 10);
JFrame frame = new JFrame("My Drawing");
Canvas canvas = new Draw();
canvas.setSize(600, 600);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
canvas.paint(canvas.getGraphics(), array);
and this is the Draw class:
public class Draw extends Canvas
{
/**Draws the graphs
*
*/
private static final long serialVersionUID = 1L;
public void paint(Graphics g, int[] array)
{
for(int x = 0; x<array.length; x++)
{
g.fillRect(x, 0, 10, array[x]);
}
}
}
I tried changing the canvas object to Draw canvas = new Draw() and that didn't result in an error but it wasn't able to draw anything on the canvas when I did that. I also tried @Override but that doesn't allow me to add any extra parameters to the method.
Currently your new Draw()
is declared as a Canvas
object. If you change the declaration to Draw canvas = new Draw();
you can call your method.
Edit: The problem is, that paint(Graphics g)
is an internal method called by Swing, when the component will be rendered by the framework. Your paint(Graphics g, int[] array)
method doesn't change the render process. You wan't to provide the paramters for creating the Drawing before paint(Graphics g)
is called. Here is an very simple example:
public class Draw extends Canvas {
private static final long serialVersionUID = 1L;
private int[] array;
public Draw(int[] array) {
this.array = array;
}
@Override
public void paint(Graphics g) {
for (int x = 0; x < array.length; x++) {
g.fillRect(x, 0, 10, array[x]);
}
}
}
And then you create your drawing with Canvas draw = new Draw(array)
instead. This simple example works as long as the Drawing doesn't have to display a different array while the Gui is running. (For exaple if a new array was created with a button press and you want to display it.)